[metapost] Decimal numbers

Troy Henderson thenders at gmail.com
Sat Nov 12 09:35:27 CET 2011


> I'm a 2nd day METAPOST user. I wonder how to get a number rounded to a
> desired number of decimal places.

The format package can do this for you already.  It is part of the base
MetaPost system.  You can use it in the following way:

input format;
show roundd(x,d);

where x is the number you want to round to d decimal places.  Note that
d could be positive, 0, or negative.  Positive d acts as you expect, d=0
rounds to the nearest ones place, and negative d rounds to the nearest
10^(-d) place.

> The labels in the example above are as follows:
>   "0, 0.1, 0.2,..., 0.9, 1"
> but the desired output is:
>   "0.0, 0.1, 0.2,..., 0.9, 1.0"

label.bot(format("%1f",i/10), (i,0)*ux); % Also requires "input format;"

> or even better:
> ".0, .1, .2,..., .9, 1.0"

I try not to make a habit of telling people what they want to see from
their MetaPost output (since MetaPost is so flexible), but as a
mathematician myself, I detest decimals without the leading 0 in the
ones place because if the print is bad, the decimal point might not show
up well and a number like .2 might be viewed as 2 instead of 0.2.
Therefore, it is my opinion that a leading 0 should be present when a
decimal d is such that -1<d<1.

--
Troy


More information about the metapost mailing list