go

Round numbers in Go

natamacm

natamacm

Posted on May 10, 2020

Round numbers in Go

Go (golang) lets you round floating point numbers. To do so, you need to import the math module.

The official math package provides methods for rounding math.Ceil() up and math.Floor() down.

package main

import (
 "fmt"
 "math"
)

func main(){
 x := 1.1
 fmt.Println(math.Ceil(x))  // 2
 fmt.Println(math.Floor(x))  // 1
}

Note that it is not a true integer that is returned after taking the whole, but a float64 type, so you need to convert it manually if you need an int type.

golang doesn't have a python-like round() function, and searched a lot of them to find a refreshing one: first +0.5, then round down!

It's incredibly simple, and there's nothing wrong with thinking about it:

func round(x float64){
    return int(math.Floor(x + 0.5))
}

In a program that would look like:

package main

import (
 "fmt"
 "math"
)

func round(x float64) int{
    return int(math.Floor(x + 0.5))
}

func main(){
 fmt.Println(round(1.4))
 fmt.Println(round(1.5))
 fmt.Println(round(1.6))
}

Related links:

πŸ’– πŸ’ͺ πŸ™… 🚩
natamacm
natamacm

Posted on May 10, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024