SoFunction
Updated on 2025-03-05

How to retain golang float64 2 decimal places through function (method summary)

Retain golang float64 by function

After any language does floating point calculation, there is a problem with the accuracy of the calculation results. For example, after using golang to add or subtract two decimal values ​​found from the mysql database, the result of the period must be two decimals, but the result calculated by golang will have many digits, such as:

1725577.59 - 1381341.21  = 344236.3800000001

The result will be 10 decimal places. This result is definitely not what we want. We only need the last two digits of the result, and the result of the last two digits is also accurate.

344236.38

This is how to do golang float64 and retain 2 decimal places after calculation.

func Decimal(num float64) float64 {
	num, _ = (("%.2f", num), 64)
	return num
}

Golang's float type retains 2 decimal places

value, _ = (("%.2f", 0.2223), 64)
   (value)

float64 in go language retains 2 decimal places

func Decimal(value float64) float64 {
    return (value*1e2+0.5) * 1e-2
}

Adding 0.5 is for rounding. If you want to keep a few decimal places, just change 2.

This version has a question about floating-point number accuracy, and there are often results similar to 13.000000001.

The following is to first retain two decimal places through Sprintf and then convert them to float64.

func Decimal(value float64) float64 {
    value, _ = (("%.2f", value), 64)
    return value
}

This is the article about retaining golang float64 with 2 decimal places through functions. For more related golang float64 with 2 decimal places, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!