help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: numerical values


From: Rob Mahurin
Subject: Re: numerical values
Date: Fri, 21 Mar 2008 14:33:08 -0400

On Mar 20, 2008, at 9:47 AM, Przemek Klosowski wrote:
As Ben pointed out, printf formats easily control the
number of decimal places, as shown above. It is even
possible to provide that number at runtime:

  sprintf('%7.*f', 2, 123.4567)   -->    123.46
  sprintf('%7.*f', 3, 123.4567)   -->    123.457


Limiting the total number of decimal places is trickier: the printf
formats don't seem to allow this control.

%g does this.

        octave:1> a = 123.456789             ---> a =  123.46
        octave:2> printf("%7g\n",a)                ---> 123.457
        octave:3> printf("%10g\n",a)               --->    123.457
        octave:4> printf("%10.2g\n",a)             --->    1.2e+02
        octave:5> printf("%10.3g\n",a)             --->        123
        octave:6> printf("%10.5g\n",a)             --->     123.46
        octave:7> printf("%10.7g\n",a)             --->   123.4568

You can cancel %g's zero-truncation with a %#g:

        octave:8> a = 123                    ---> a =  123
        octave:9> printf("%10.7g\n",a)             --->        123
        octave:10> printf("%#10.7g\n",a)   --->   123.0000

This is the C behavior.

Cheers,
Rob

--
Rob Mahurin
Dept. of Physics & Astronomy
University of Tennessee         phone: 865 207 2594
Knoxville, TN 37996             email: address@hidden



reply via email to

[Prev in Thread] Current Thread [Next in Thread]