Round all decimal points in Golang [duplicate]

一个人想着一个人 提交于 2020-06-28 04:11:19

问题


I'm trying to unconventionally round all the digits in a float64 variable. For example:

3.4444445 --> 3.5

I want to do this without converting it into a string!


回答1:


Golang's math library provides a Round function. However, it rounds the float64 to an int, meaning decimals are lost.

A quick workaround around this would be to multiple the number by the number of decimals you want to save, then round, then divide it back again:

raw := 4.335
rounded := math.Round(raw * 10) / 10

Will give you the desired result.

You may want to create a little helper function to round saving any number of digits:

func roundTo(n float64, decimals uint32) float64 {
    return math.Round(n * float64(decimals)) / float64(decimals)
}

Usage:

roundTo(4.2655, 1) // 4.3
roundTo(4.3454, 3) // 4.345


来源:https://stackoverflow.com/questions/52048218/round-all-decimal-points-in-golang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!