How can we truncate float value (float32, float64) to a particular precision in Golang?

Given a floating-point value, we have to truncate it to a particular precision in Golang.
Submitted by IncludeHelp, on October 24, 2021

In the Go programming language, a float value (float32, float64) can be truncated by using the format verb %f with precision value (i.e., %.nfn is the number of precisions).

Consider the below examples,

Example 1:

// Golang program to truncate float value
// to a particular precision

package main

import (
	"fmt"
)

func main() {
	var x float32 = 123.456789
	var y float64 = 123456789.90123456

	// Printing the values without
	// truncating
	fmt.Println("Without truncating...")
	fmt.Printf("x: %f, y: %f\n", x, y)

	// Printing the truncatedvalues
	fmt.Println("Truncated values...")
	fmt.Printf("x: %.2f, y: %.2f\n", x, y)
	fmt.Printf("x: %.3f, y: %.3f\n", x, y)
	fmt.Printf("x: %.5f, y: %.5f\n", x, y)
}

Output:

Without truncating...
x: 123.456787, y: 123456789.901235
Truncated values...
x: 123.46, y: 123456789.90
x: 123.457, y: 123456789.901
x: 123.45679, y: 123456789.90123

Example 2:

// Golang program to truncate float value
// to a particular precision

package main

import (
	"fmt"
)

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

Output:

3.33

Golang FAQ »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.