Round float to 2 decimals
While doing some small programming exercises learning Go, I ran into the problem of rounding a float to 2 decimals.
While examining my options and go and doing some searching I fell over this solution:
x := 12.3456 fmt.Println(math.Floor(x*100)/100) // 12.34 (round down) fmt.Println(math.Round(x*100)/100) // 12.35 (round to nearest) fmt.Println(math.Ceil(x*100)/100) // 12.35 (round up)
The concept is quote simple. If you have a float, like the notorious Pi, with 5 decimals:
3.14159 and you for some nefarious mathical reason want to settle with 2 decimals.
- Multiply by
3.14159 * 100 = 314.159
- Round the number using the standard mechanism for this:
Math.round(314.159);and you get
314, since our round function now works with integers
- Divide by
314 / 100and you get
For 3 decimals, simply use
1000 as your multiplier and divisor.
console.log(Math.round(3.1415926535*1000)/1000); // 3.142