How to add zero after a decimal point to float type using decimal lib

1,138 views
Skip to first unread message

pravin chaudhary

unread,
Oct 13, 2022, 5:05:34 AM10/13/22
to golang-nuts

I need to add zeroes after a decimal point to a float type but not able to do so.

For instance I have a int value of 500 and need to convert this to 5.00 (type must be float) and need to use decimal lib

fmt.Printf("%.2f", value) -> this will do formatting but type is not float which is the requirement.

Can anyone please help on this.

Thanks,
Pravin

Brian Candler

unread,
Oct 13, 2022, 5:25:50 AM10/13/22
to golang-nuts
Please try to give your "requirement" in a more meaningful form.

> fmt.Printf("%.2f", value) -> this will do formatting but type is not float which is the requirement.

This doesn't mean anything without context.  If I write:

var value float64
fmt.Printf("%.2f", value)

then 'value' clearly *is* a float.

> For instance I have a int value of 500 and need to convert this to 5.00 (type must be float)

i := 500
v := float64(i) / 100
fmt.Printf("%.2f", value)


> and need to use decimal lib

That presupposes a solution.  This might be an XY problem, i.e. you are choosing the wrong way to approach the issue.

Is the issue that you are worried about inexact calculations in floating point?  And you just want to format whole numbers of cents for display, so that they appear as dollars and cents? Then maybe you want something like this:

    i := 500
    dollars := i / 100
    cents := i % 100
    fmt.Printf("%d.%02d\n", dollars, cents)

or:

    v := fmt.Sprintf("%03d", i)
    v = v[0:len(v)-2] + "." + v[len(v)-2:]
    fmt.Println(v)

Reply all
Reply to author
Forward
0 new messages