# formatting numbers in sagetex

If I put (for example) \sage{1.2*V} in my .tex file the resulting pdf has

1.20000000000000 V

How can I tell it to not print trailing zeros?

Thanks.

edit retag close merge delete

Sort by » oldest newest most voted

I worked on a ticket to help with this a while ago: http://trac.sagemath.org/sage_trac/ti...

You can see a comment from Carl Witty that gives a good approach: (I really like his option 1). Basically, it allows for setting options for printing any numbers from a RealField.

For an individual number, you're looking for the skip_zeroes argument to str:

sage: a=1.2
sage: a
1.20000000000000
sage: a.str(skip_zeroes=True)
'1.2'

Alternatively, this is the default behavior for python floats (as opposed to Sage floating point numbers), so if you either turn off the preparser or use python floats, you'll get what you want:

sage: float(1.2)*x
1.2*x
sage: preparser(False)
sage: 1.2*x
1.2*x
more

Depending on the type of calculations, you might be able to work in RDF, for example, or in RealField(23), replacing 23 by whatever number gives you the desired precision.

more

In addition to the nicer output without trailing zeros, using RDF will usually make everything faster.

( 2015-03-11 06:17:53 -0500 )edit

I find that the easiest way to to convert to a python floating point before printing.

float(24/5)          #-> 4.8
"%.4f" % float(26/3) #-> 8.6667
more

Try \sage{(1.2).n(6)*V}. The .n(6) command specifies the number of significant bits used to represent the number. As a rule of thumb 3 bits ~ 1 digit.

more

Yes, that would work for this example, but what in the general case \sage{x} where x is the result of some calculation I can't just call .n(6) on the result because there are non-numeric variables. Does this mean that I should call .n on all the floating point numbers as they enter into the calculation?

( 2012-11-08 10:29:21 -0500 )edit

I think so, yes. In general you know from the start if the result will be numeric or not. And most of the time you also know the precision you are aiming at.

( 2012-11-09 00:05:25 -0500 )edit