Home   Archive   Permalink

Format a number to two decimals

How do I format a number to two decimals? I really looked through all the documentation but I cannot find anything about it. For example displaying 12.1 as 12.10, or writing it to a file as 12.10. Or 3 as 3.00. How would I be able to do that?
Thank you!

posted by:   Jay     13-May-2021/14:41:13-7:00

I remember struggling with that in the past, too. Unfortunately, it's different across REBOL versions.
In REBOL 3, you would probably use the FORMAT dialect, which has a /PAD refinement. But I never used it, so I know very little about it.
It was made because REBOL 2 has little for it, so you usually have to cook something up yourself there.

posted by:   Kaj     13-May-2021/16:31:18-7:00

Oh that's a shame. When I open rebol.exe, it shows REBOL/View, so I guess that FORMAT command is not available to me. Is there a way to determine how many decimals a variable has? Because then you can turn it into a string and add zeros at the end.

posted by:   Jay     13-May-2021/17:30:14-7:00

So I had the idea to use remainder (//) to determine the number of decimals, then turn it into a string and add zeros accordingly. But since I want to format the number into 2 decimals, I decided to use the following (ugly, but functional) code:
number: "2.1"
number: to-money number
number: to-string number
remove/part number 1
alert number
Works really nice!

posted by:   Jay     14-May-2021/2:55:30-7:00

Found two applicable money functions of mine:
round-money: func [ ; To two decimal places
    money [money! decimal! integer!]
    (to-integer (either money? money [money/2] [money]) * 100 + (0.5 * sign? money)) / 100
form-money: func [
    money [money! decimal! integer!]
    if money? money [money: money/2] ; For R2
    rejoin [
        either negative? money [#"-"] [""] ; Optionally different representation
        absolute to-integer money
        #"," ; Dutch!
        pad (to-integer (absolute money) * 100 + 0.5) // 100 2 ; Cents
Of course, if you're in an anglo-saxon country, you can replace the comma with a dot.

posted by:   Kaj     6-Jun-2021/7:20:23-7:00

It uses PAD:
pad: func ["Convert to string and pad to specified width."
    width [integer!]
        padding [char!]
    /local num?
][    ; FIXME: left-zero-padding of negative numbers, right-zero-padding of integers
    num?: number? item
    unless with [padding: either num? [#"0"] [#" "]]
    item: form item
    head insert/dup
        either any [all [num? not right] left] [item] [tail item]
        width - length? item

posted by:   Kaj     6-Jun-2021/7:23:31-7:00

>> to2dec: func [i [decimal! integer!]][ head insert back back tail form to integer! i * 100 "."]
== #[action! {to2dec} [i]]
>> to2dec 12.1
== "12.10"
>> to2dec 3
== "3.00"

posted by:   Graham     25-Dec-2021/15:03:53-8:00



Type the reverse of this captcha text: "s s e r p m o c"