SoFunction
Updated on 2025-03-03

The perfect solution to keep N bits after decimal point in go floating point to string

Recently, I encountered float to string many times in the project, and at the same time, I required to keep a few decimal places and remove the scene of 0 after the decimal point.

Although the question is very simple, I became a little unfamiliar after not dealing with this kind of scene after a long time. I searched it myself, but many of the answers were not satisfied with. Here are some tips for your own approach. If there is a better solution, please give me some advice.

// The main logic is to multiply first, then divide it back, which achieves the effect of retaining N-digit decimalsfunc FormatFloat(num float64, decimal int) string {
 // Multiply 1 by default d := float64(1)
 if decimal > 0 {
  // N-power of 10  d = math.Pow10(decimal)
 }
 // It is to return the integer part of the floating point number // After deciding back, the invalid 0 after the decimal point will no longer exist return ((num*d)/d, 'f', -1, 64)
}

Some other commonly used demos for formatting floating point numbers

// 2 represents accuracy, this method will have 0 invalid after the decimal point (123.123 'f', 2, 64)
 // The effect is the same as above ("%.2f", 123.123)
 // g can remove the invalid 0 after the decimal point ("%g", 123.00)
 // The effect is the same as above, 0 can be removed, but the effect of retaining the specified number of digits cannot be achieved. (a, 'g', -1, 64)

In fact, using the above examples can achieve the initial effect

ps: Let's take a look at golang floating point number to retain n decimals

Programmers' natural enemy products, just like the UI girl's party father, always mentions some requirements you don't want to write, and you can't do it. For example, a certain value passes through ÎÒ´òµÄ¾ÍÊÇÂÒÂë, first keep 3 decimal places, then pass %¥#@%&*%¥#%, keep 2 decimal places, round after passing through 10. . . . .

Therefore, there is the following n position rounding

func ChangeNumber(f float64, m int) string {
n := (f, ‘f', -1, 32)
if n == “” {
return “”
}
if m >= len(n) {
return n
}。
newn := (n, “.”)
if len(newn) < 2 || m >= len(newn[1]) {
return n
}
return newn[0] + “.” + newn[1][:m]
}

Why return string type? ? Because after various calculations of floating point numbers, the accuracy is likely to be lost. One of the methods is to perform an operation and convert it into a string type, then convert it from the string type to float type, and then perform the next operation, firmly ✧(≖ ◡ ≖✿)

Summarize

This is the article about the perfect solution to retaining N bits after the decimal point in go floating point to string. For more related contents of go floating point to string, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!