How to round a decimal to 2 decimal places in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"math"
)

func roundToTwoDecimalPlaces(value float64) float64 {
	return math.Round(value*100) / 100
}

func main() {
	number := 2.431;
	rounded := roundToTwoDecimalPlaces(number)
	fmt.Printf("Rounded: %.2f\n", rounded)
	
	number = 2.457;
	rounded = roundToTwoDecimalPlaces(number)
	fmt.Printf("Rounded: %.2f\n", rounded)
}


/*
run:

Rounded: 2.43
Rounded: 2.46

*/

 



answered May 15, 2025 by avibootz

Related questions

1 answer 66 views
1 answer 84 views
1 answer 74 views
1 answer 178 views
1 answer 198 views
3 answers 226 views
2 answers 174 views
...