Golang : Display float in 2 decimal points and rounding up or down
We will cover 2 items for this tutorial.
First, we will learn how to display a float number in decimal points with the fmt.Printf()
function. The %0.2f
inside fmt.Printf()
function tells Golang to display up to 2 decimal points. To increase the precision, simply adjust the number from %0.2f
to %0.#f
. # being the number of digits to display the after the decimal point.
Next, Golang math package lacks of functions to do rounding on float numbers. The code example below has 3 functions - one to do rounding, next for rounding up and another to do rounding down for a float value.
Here you go!
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.Printf("%0.2f \n", Round(f)) // round half
fmt.Printf("%0.2f \n", RoundUp(f, 2))
fmt.Printf("%0.2f \n", RoundDown(f, 2))
}
NOTE : Change value of f to -123.123456
and see how it goes.
Output :
123.12
123.00
123.13
123.12
References :
http://golang.org/pkg/math/#Ceil
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
+4.1k Golang : Display packages names during compilation
+17.1k Golang : Generate thumbnails from images
+6.5k Golang : What fmt.Println() can do and println() cannot do
+6.3k Android Studio : AlertDialog to get user attention example
+8.4k Golang : How to protect your source code from client, hosting company or hacker?
+5.1k Golang : Process non-XML/JSON formatted ASCII text file example
+9.1k Golang : Allow Cross-Origin Resource Sharing request
+5.7k Fix sudo yum hang problem with no output or error messages
+9.4k Golang : Get UDP client IP address and differentiate clients by port number
+4.5k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+13.1k Golang : GUI with Qt and OpenCV to capture image from camera
+33.8k Golang : How to split or chunking a file to smaller pieces?