Today I Learned: collection of notes, tips and tricks and stuff I learn from day to day working with computers and technology as an open source contributor and product manager

View project on GitHub

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 great thing about it, apart from it’s simplicity is that it is not Go specific. JavaScript has the exact same problem with standard library rounding functions, working only with integers.

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.

  1. Multiply by 100: 3.14159 * 100 = 314.159
  2. 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
  3. Divide by 100: 314 / 100 and you get 3.14

For 3 decimals, simply use 1000 as your multiplier and divisor.

// 3.142