Skip to content

How to Convert Float to N Decimal Place String in Go

Remembering the conversion solutions in golang is not easy, but the fmt package is always with us. By using the Sprintf method it is super easy to convert and round a float type into string type:

fmt.Sprintf("%.2f", floatNumber) // round up and keep 2 decimal

Example code:

package main

import "fmt"

func main() {

	// float number
	floatNumber := 234.5698745987

	// round and keep 2 decimal
	twoDecimmalString := fmt.Sprintf("%.2f", floatNumber)

	// round and keep 4 decimal
	fourDecimalString := fmt.Sprintf("%.4f", floatNumber)

	fmt.Println(twoDecimmalString)
	fmt.Println(fourDecimalString)
}

Leave a Reply

Your email address will not be published. Required fields are marked *