Question

I'm trying to get printf to diplay number of a constant length (in characters) in OS X Terminal. So if I specify three character length, then the number will be I'd like to achieve this:

100.4125 -> 100
1.5131   -> 1.51
59.9159  -> 59.9

print substr(0,4) would nearly achieve this, but I would be left with a decimal pointer after the 100.

Was it helpful?

Solution

Using the specifier g or G will format to significant digits. The following example will format to 3 significant figures.

printf("ans: %.3g", 100.4125)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top