Golang : Round float to precision example
Just an add on for my previous tutorial on how to round up or down a float number. For this short tutorial, we will learn how to round float numbers to certain precision.
Instead of using
fmt.Printf("%0.2f \n", f)
fmt.Printf("%0.2f \n", Round(f)) // round half
fmt.Printf("%0.2f \n", RoundUp(f, 2)) // change 2 to 5 will have no effect
fmt.Printf("%0.2f \n", RoundDown(f, 3)) // change 3 to 4 will have no effect
which will output the precision up to 2 decimal point no matter how you instruct the Round, RoundUp and RoundDown functions.
This is because of fmt.Printf(%0.2\n)
will always overrule the final display format.
To fix this problem or to display the precision properly, you will have to use fmt.Println()
instead.
var f float64 = 123.123456
fmt.Printf("%0.2f \n", f)
fmt.Println(Round(f)) // round half
fmt.Println(RoundUp(f, 4)) // up to precision 4
fmt.Println(RoundDown(f, 4)) // up to precision 4
Output :
123.12
123
123.1235
123.1234
Here's the full code :
package main
import (
"fmt"
"math"
)
func Round(input float64) float64 {
if input < 0 {
return math.Ceil(input - 0.5)
}
return math.Floor(input + 0.5)
}
func RoundUp(input float64, places int) (newVal float64) {
var round float64
pow := math.Pow(10, float64(places))
digit := pow * input
round = math.Ceil(digit)
newVal = round / pow
return
}
func RoundDown(input float64, places int) (newVal float64) {
var round float64
pow := math.Pow(10, float64(places))
digit := pow * input
round = math.Floor(digit)
newVal = round / pow
return
}
func main() {
var f float64 = 123.123456
fmt.Printf("%0.2f \n", f)
fmt.Println(Round(f)) // round half
fmt.Println(RoundUp(f, 4))
fmt.Println(RoundDown(f, 4))
}
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+15.3k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+17.1k Golang : Check if IP address is version 4 or 6
+15k Golang : Find location by IP address and display with Google Map
+9.2k Golang : Play .WAV file from command line
+7.1k Golang : How to detect if a sentence ends with a punctuation?
+15.6k Golang : Update database with GORM example
+6.7k Golang : How to setup a disk space used monitoring service with Telegram bot
+6.7k Golang : Fibonacci number generator examples
+8.6k Golang : Find network service name from given port and protocol
+7.9k Android Studio : Rating bar example
+15.9k Golang : How to check if input from os.Args is integer?
+5.4k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)