How to round a floating point number and remove digits after decimal point in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"math"
)

func main() {
	x, y, z := 4.311, 6.500, 9.811

	fmt.Printf("%.3f\n", math.Trunc(x))
	fmt.Printf("%.3f\n", math.Trunc(y))
	fmt.Printf("%.3f\n", math.Trunc(z))

	x, y, z = -4.311, -6.500, -9.811

	fmt.Printf("%.3f\n", math.Trunc(x))
	fmt.Printf("%.3f\n", math.Trunc(y))
	fmt.Printf("%.3f\n", math.Trunc(z))
}



/*
run:

4.000
6.000
9.000
-4.000
-6.000
-9.000

*/

 



answered Sep 18, 2024 by avibootz
...