Go: Converting float64 to int with multiplier

后端 未结 3 449
孤街浪徒
孤街浪徒 2021-01-14 05:42

I want to convert a float64 number, let\'s say it 1.003 to 1003 (integer type). My implementation is simply multiply the float64

3条回答
  •  [愿得一人]
    2021-01-14 06:13

    This is probably likely a problem with floating points in general in most programming languages though some have different implementations than others. I wouldn't go into the intricacies here but most languages usually have a "decimal" approach either as a standard library or a third party library to get finer precision.

    For instance, I've found the inf.v0 package largely useful. Underlying the library is a Dec struct that holds the exponents and the integer value. Therefore, it's able to hold 1.003 as 1003 * 10^-3. See below for an example:

    package main
    
    import (
        "fmt"
    
        "gopkg.in/inf.v0"
    )
    
    func main() {
        // represents 1003 * 10^-3
        someDec := inf.NewDec(1003, 3)
    
        // multiply someDec by 1000 * 10^0
        // which translates to 1003 * 10^-3 * 1000 * 10^0
        someDec.Mul(someDec, inf.NewDec(1000, 0))
    
        // inf.RoundHalfUp rounds half up in the 0th scale, eg. 0.5 rounds to 1
        value, ok := someDec.Round(someDec, 0, inf.RoundHalfUp).Unscaled()
        fmt.Println(value, ok)
    }
    

    Hope this helps!

提交回复
热议问题