Page 1 of 1
decimal places
Posted: Tue Jan 03, 2012 7:35 pm
by adventuresofgreg
Hello: Is there an easy way to force LiveCode to display a number using a preset # of decimal places?
ie: convert 28799.2 to 28799.200
Re: decimal places
Posted: Tue Jan 03, 2012 8:02 pm
by jmburnod
Hi
I'm not a specialist about this but i believe numberformat is a way to do that.
Best regards
Jean-Marc
Re: decimal places
Posted: Wed Jan 04, 2012 12:38 pm
by Klaus
Hi Greg,
yep, Jean-Marc is right numberformat will do!
BUT setting the numberformat will only affect arihmetic operations AFTER setting numberformat,
so you need to do something like this:
...
set numberformat to "x.xxx"
put 28799.2 into tNumber
## We FAKE an arithmetic operation!
add 0 to tNumber
answer tNumber
## -> 28799.200
...
Another way is to use FORMAT, but this is still a msytery to me
Best
Klaus
Re: decimal places
Posted: Wed Jan 04, 2012 3:07 pm
by SparkOut
Numberformat will do, but to demystify
put 28799.2 into tNumber
answer format("%.3f",tNumber)
should display 28799.200
The format to use is a string "template" starting with %. Using the format template above means:
"ignore the overall length of the number because we didn't specify a length before the decimal point, we're only interested in the required precision after the point"
"precision after the decimal point to 3 decimal places because that's the number we specified after the point in the template (ie if tNumber is 28799.212345 it will be rounded to 28799.212 or 28799.21876 will be rounded to 28799.219)"
"pad the decimals with zeroes to the required precision since we used f (for floating point) indicator, not g (which is the same but ignores padding zeroes after the point)"
format returns a STRING representation of the value. (Livecode will interpret data appropriately according to what operations you are doing, so you can still do mathematical operations on the returned value, but you may need to be careful if you do other formatting, such as insert spaces and commas for 1000 separation etc.
Re: decimal places
Posted: Thu Jan 05, 2012 3:34 pm
by adventuresofgreg
Thank you - either solution works perfectly.
greg