28 Feb 11, 09:38AM
Here's a handy little script to format numbers to a given number of decimal digits; for example /echo (format_precision 123.456 1) will output 123.4 - notice that there's no rounding, you can do that on the input yourself eg (+ 123.456 0.05) in this example.
It's subject to floating point accuracy issues so there may well be artifacts that integers don't suffer from: 32-bit floats are roughly enough for 6 digits total, so eg 0.12345 should be fine as well as 123.45, but 12345.67 will start showing error buildup.
Credits to Bukz for the idea and Gibstick \:D
It's subject to floating point accuracy issues so there may well be artifacts that integers don't suffer from: 32-bit floats are roughly enough for 6 digits total, so eg 0.12345 should be fine as well as 123.45, but 12345.67 will start showing error buildup.
Credits to Bukz for the idea and Gibstick \:D
[SELECT ALL] Code:
// format input number (int/float) to a given precision
// no sanity checks on inputs, caller's responsibility
// note: format_precision -0.1 0 >>> -0
// arg1: number to convert
// arg2: precision (optional, default 0 == integer)
alias format_precision [
if (listlen $arg1) [
// if negative input, flag to prepend sign later if needed
if (<f $arg1 0) [
arg1 = (-f 0 ($arg1)); negative = 1
] [
negative = 0
]
divisor = 1000000000 // max 32-bit int order of magnitude
magnitude = 9 // 10^9 = divisor
looping = 1
while [ ($looping) ] [
if (div $arg1 $divisor) [
// found first non-zero digit, break out
looping = 0
] [
// next order of magnitude (power of 10)
divisor = (div $divisor 10)
-= magnitude 1
if (< $magnitude 0) [ looping = 0 ]
]
]
output = ""
while [ (>= ($magnitude) 0) ] [
digit = (div $arg1 $divisor)
output = (concatword $output $digit)
-=f arg1 (* $digit $divisor)
divisor = (div $divisor 10)
-= magnitude 1
]
if (strcmp $output "") [ output = "0" ]
if ($negative) [ output = (concatword - $output) ]
decimals = ""
while [ ($arg2) ] [
*=f arg1 10
digit = (div $arg1 1)
decimals = (concatword $decimals $digit)
-=f arg1 $digit
-= arg2 1
]
if (listlen $decimals) [ decimals = (concatword . $decimals) ]
output = (concatword $output $decimals)
result $output
] [
// no input, doh
result ""
]
]