[REBOL] Re: how to format decimals?
From: volker:nitsch::gmail at: 25-Apr-2005 17:11
On 4/25/05, [SunandaDH--aol--com] <[SunandaDH--aol--com]> wrote:
> Janeks:
> > Hi, Rebolers! How to format decimals to show the given number of decimal
> > fraction digits? F.ex.: format 2.3 3 => 2.300
>
> Here's a very quick and dirty method, that reuses oneliner-nfrac.r in the
> REBOL.org library -- not optimal in terms of runtime performance, but an example
> of software reuse:
>
> nfrac: func [d][length? second parse join d ".." "."]
> format: func [number [decimal!] length [integer!]
> /local res
> ][
> res: form number
> n: nfrac number
> if n > length [return copy/part res (length? res) - (n - length) ]
> loop length - n [append res "0"]
insert/dup tail res "0" length - n ;)
> res
> ]
>
> >> for n 0 5 1 [print format 1.23 n]
> 1.
> 1.2
> 1.23
> 1.230
> 1.2300
> 1.23000
>
And while looking at it, another way (only short tested):
; digs must be >= 1 !
format: func [num digs] [
int: to-integer num
frac: num - int
frac: form to-integer 10 ** digs * frac ;rebol-order ;)
insert/dup tail frac "0" digs - length? frac
rejoin ["" int "." frac]
]
for n 0 5 1 [print format 1.23 n]
gives
1.0 ;wrong, but keeps func shorter
1.2
1.23
1.229
1.2300
1.23000
> Sunanda.
> --
> To unsubscribe from the list, just send an email to
> lists at rebol.com with unsubscribe as the subject.
>
--
-Volker
Any problem in computer science can be solved with another layer of
indirection. But that usually will create another problem.
David
Wheeler