Ask Your Question

formatting numbers in sagetex

asked 2012-11-08 07:57:18 -0500

naegling gravatar image

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?


edit retag flag offensive close merge delete

4 answers

Sort by ยป oldest newest most voted

answered 2012-11-09 04:04:53 -0500

Jason Grout gravatar image

updated 2012-11-09 04:07:28 -0500

I worked on a ticket to help with this a while ago:

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
sage: a.str(skip_zeroes=True)

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
sage: preparser(False)
sage: 1.2*x
edit flag offensive delete link more

answered 2012-11-09 06:37:01 -0500

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.

edit flag offensive delete link more


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

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

answered 2015-03-10 17:50:08 -0500

Kevin Cox gravatar image

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
edit flag offensive delete link more

answered 2012-11-08 09:36:06 -0500

Dirk Danckaert gravatar image

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.

edit flag offensive delete link 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?

naegling gravatar imagenaegling ( 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.

Dirk Danckaert gravatar imageDirk Danckaert ( 2012-11-09 00:05:25 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2012-11-08 07:57:18 -0500

Seen: 721 times

Last updated: Mar 10 '15