I want to print two digits after decimal after rounding in GO language.. e.g 1.222225 should be printed as 1.22 1.356 should be printed as 1.36
How can i do it?
If you use the fmt.Printf
function there is syntax in the formatting string that lets you print floats to a given level of precision like this. The general syntax is %.[numberofdigits]f
.
Examples:
fmt.Printf("%.2f" 1.2222225) // output: 1.22
fmt.Printf("%.2f", 1.356) // output: 1.36
One thing to note is that the round doesn't "carry"
fmt.Printf("%.1f", 1.346)
Will output 1.3, not 1.4. Additionally, negative numbers will behave as expected:
fmt.Printf("%.2f", -1.356) // output: -1.36
You may want to use a Decimal64p2
type of decimal with fixed .00 precision - https://github.com/strongo/decimal
Comparing to fmt.Printf("%.1f", 1.346)
it will round correctly.
It is efficient for storing exact amounts of money.