How to format decimal in Go

3 Answers

0 votes
package main

import (
	"fmt"
)

func main() {
	value := 123.456789

	// Print with 2 decimal places
	fmt.Printf("%.2f\n", value)

	// Print with 4 decimal places
	fmt.Printf("%.4f\n", value)

	// Store formatted string with 2 decimal places
	formattedValue := fmt.Sprintf("%.2f", value)
	fmt.Println(formattedValue)
}


 
 
/*
run:
 
123.46
123.4568
123.46

*/

 



answered May 6, 2025 by avibootz
0 votes
package main

import (
	"fmt"
	"strconv"
)

func main() {
	value := 123.456789

	// Format with 2 decimal places
	formattedValue := strconv.FormatFloat(value, 'f', 2, 64)
	fmt.Println(formattedValue)

	// Format with 4 decimal places
	formattedValue = strconv.FormatFloat(value, 'f', 4, 64)
	fmt.Println(formattedValue)
}


 
 
/*
run:
 
123.46
123.4568

*/

 



answered May 6, 2025 by avibootz
0 votes
package main

import (
	"fmt"
	"math"
)

func main() {
	value := 123.456789

	// Round to 2 decimal places
	roundedValue := math.Round(value*100) / 100
	fmt.Printf("%.2f\n", roundedValue)

	// Round to 4 decimal places
	roundedValue = math.Round(value*10000) / 10000
	fmt.Printf("%.4f\n", roundedValue)
}


 
 
/*
run:
 
123.46
123.4568

*/

 



answered May 6, 2025 by avibootz
...