Enjoy! Fixed-width decimal printout, with decimals
localroger
Posts: 3,452
You might have noticed that most of the public output objects have nice fixed width binary and hex outputs but the decimal output is variable-width so you can't use it to create nice formatted displays.
*cough*
You can consider this public domain, as there isn't enough here to justify a copyright claim.
Post Edited (localroger) : 8/17/2009 4:55:05 PM GMT
*cough*
PUB fdec(value, len, dp) | p, fnumbuf[noparse][[/noparse] 4 ] { Print a formatted signed decimal number The dec method provided with most output objects inexplicably doesn't do fixed length. This version also inserts an optional decimal point. A negative dp specifies dead zeroes, e.g. dp=-3 returns 000 instead of 0. Observe the sneakiness with which I allocate a temporary string buffer... fnumbuf thinks it's 4 longs but I use it as bytes so I can write the decimal out backward. Note that you can't return a pointer to this string since it's on the stack and goes away when we return; to do that you must create a buffer outside of this routine and add its location to the parameter list. First we prep the buffer with any leading zero and decimals that might be called for, then write the number down backward skipping over the decimal and skipping over any remaining zeroes for the minus sign. } bytefill(@fnumbuf," ",14) byte[noparse][[/noparse]@fnumbuf+14] := 0 p := @fnumbuf + 13 if dp > 0 repeat dp byte[noparse][[/noparse]p] := "0" p-- byte[noparse][[/noparse]p] := "." p-- byte[noparse][[/noparse]p] := "0" p-- elseif dp < 0 repeat -dp byte[noparse][[/noparse]p] := "0" p-- else byte[noparse][[/noparse]p] := "0" p-- rdec(value, @fnumbuf+13) str(@fnumbuf + 14 - len) PRI rdec(value, atloc) | s { This is works like dec but writes the number to memory down from the starting atloc. It will not write over a decimal point; the string should be pre-loaded with any necessary leading zeroes and decimals. There are no controls so be sure the buffer is large enough to handle a signed, decimalled 9-digit number. } s := 0 if value < 0 -value s := "-" repeat while value <> 0 'skip over decimal if byte[noparse][[/noparse]atloc] == "." atloc -- byte[noparse][[/noparse]atloc] := value // 10 + "0" atloc -- value /= 10 if s 'skip over any non space before writing sign repeat while byte[noparse][[/noparse]atloc] <> " " atloc -- byte[noparse][[/noparse]atloc] := s
You can consider this public domain, as there isn't enough here to justify a copyright claim.
Post Edited (localroger) : 8/17/2009 4:55:05 PM GMT