A perfect solution for go floating point Numbers to retain the N bit after the decimal point

  • 2020-10-23 21:01:36
  • OfStack

There have been a number of recent scenarios in which float turns to string and requires a few decimal places to be kept and zero to be removed from the decimal point

Although the question is very simple, but after a long time did not deal with this scene is a little rusty, I also searched 1, many answers are not satisfied. Here post 1 of my own ways, if there is a better solution, please give me more advice


//  The main logic is to multiply first, trunc And then you go back and you get retention N The effect of a decimal 
func FormatFloat(num float64, decimal int) string {
 //  The default by 1
 d := float64(1)
 if decimal > 0 {
  // 10 the N To the power 
  d = math.Pow10(decimal)
 }
 // math.trunc Returns the integer portion of a floating-point number 
 //  If I divide it back, it doesn't work after the decimal point 0 It doesn't exist 
 return strconv.FormatFloat(math.Trunc(num*d)/d, 'f', -1, 64)
}

The other 1 is demo, which is commonly used to format floating point Numbers


// 2 It's the precision, it's not going to work after the decimal point 0 In the case 
 strconv.FormatFloat(123.123 'f', 2, 64)
 //  The effect same as above 
 fmt.Sprintf("%.2f", 123.123)
 // g We can get rid of the invalid decimal point 0
 fmt.Sprintf("%g", 123.00)
 //  Ditto. You can remove it 0 , but the effect of retaining the specified number of digits is not achieved 
 strconv.FormatFloat(a, 'g', -1, 64)

The examples above can also be used flexibly to achieve the initial effect

ps: Let's take a look at golang floating-point Numbers and keep the n decimal place

Programmers' natural enemies are product classmates, just like the father of Party A of UI girl, who always mention some requirements that you don't want to write, but can't do it, such as some numerical value passing Î Ò ´ O&ES en; Ä ¾ Í Ê Ç Â Ò Â ë , retain 3 decimal places, and then go through %¥#@% & *%¥#%, and retain 2 decimal places, after passing 䅂 The & # 17201; The & # 12851; � the & # 41189; The & # 42429; � the & # 65533; , round...

Therefore, we have the n bit integer below


func ChangeNumber(f float64, m int) string {
n := strconv.FormatFloat(f,  ' f', -1, 32)
if n ==  ""  {
return  "" 
}
if m >= len(n) {
return n
} . 
newn := strings.Split(n,  " . " )
if len(newn) < 2 || m >= len(newn[1]) {
return n
}
return newn[0] +  " . "  + newn[1][:m]
}

Why y return string type? Because floating point Numbers are likely to lose precision after performing various computations, one method is to convert to string type after one operation, then to float type after a string type, and then to perform the following operation, stable ✧ (& # 8790; The & # 9697; The & # 8790; The & # 10047;)

conclusion


Related articles: