Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we truncate float64 type to a particular precision?

package main  import (     "fmt"     "strconv"     )  func main() {     k := 10/3.0     i := fmt.Sprintf("%.2f", k)     f,_ := strconv.ParseFloat(i, 2)     fmt.Println(f) } 

I had to write the program above to decrease the precision of a go float64 variable to 2. In this case I was using both strconv and fmt. Is there some other logical method by which it can be done?

like image 728
George Thomas Avatar asked Aug 22 '13 20:08

George Thomas


People also ask

How do you truncate a float to two decimal places in Python?

Just use the formatting with %. 2f which gives you round down to 2 decimal points.

How do you truncate a float?

Use the int Function to Truncate a Float in Python The built-in int() function takes a float and converts it to an integer, thereby truncating a float value by removing its decimal places. What is this? The int() function works differently than the round() and floor() function (which you can learn more about here).


2 Answers

The following code should work for a lot of simple use cases with relatively small numbers and small precision inputs. However, it may not work for some uses cases because of numbers overflowing out of the range of float64 numbers, as well as IEEE-754 rounding errors (other languages have this issue as well).

If you care about using larger numbers or need more precision, the following code may not work for your needs, and you should use a helper library (e.g. https://github.com/shopspring/decimal).

I picked up a one-liner round function from elsewhere, and also made toFixed() which depends on round():

func round(num float64) int {     return int(num + math.Copysign(0.5, num)) }  func toFixed(num float64, precision int) float64 {     output := math.Pow(10, float64(precision))     return float64(round(num * output)) / output } 

Usage:

fmt.Println(toFixed(1.2345678, 0))  // 1 fmt.Println(toFixed(1.2345678, 1))  // 1.2 fmt.Println(toFixed(1.2345678, 2))  // 1.23 fmt.Println(toFixed(1.2345678, 3))  // 1.235 (rounded up) 
like image 186
David Calhoun Avatar answered Sep 24 '22 21:09

David Calhoun


You don't need any extra code ... its as simple as

import (     "fmt" )  func main() {     k := 10 / 3.0     fmt.Printf("%.2f", k) } 

Test Code

like image 23
Baba Avatar answered Sep 23 '22 21:09

Baba