drxrgundk062317205 2019-09-24 21:56
浏览 111

我们应该如何计算货币(十进制,大浮点数)

Can someone tell the right way to calculate finance data in Go. I tryed to use big.Float but prob I miss something. The core goal is to calculate numbers with flaoting point and precision from 2 to 4 without any losses. 0.15 + 0.15 always should be 0.30. float try: https://play.golang.org/p/_3CXtRRNcA0 big.Float try: https://play.golang.org/p/zegE__Dit1O

  • 写回答

2条回答 默认 最新

  • doulu3865 2019-09-24 22:25
    关注

    Floating-point is imprecise. Use integers (int64) scaled to cents or fractional cents.


    For example, cents,

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        cents := int64(0)
        for i := 0; i <= 2; i++ {
            cents += 15
            fmt.Println(cents)
        }
        fmt.Printf("$%d.%02d
    ", cents/100, cents%100)
    }
    

    Playground: https://play.golang.org/p/k4mJZFRUGVH

    Output:

    15
    30
    45
    $0.45
    

    For example, hundredths of a cent rounded,

    package main
    
    import "fmt"
    
    func main() {
        c := int64(0) // hundredths of a cent
        for i := 0; i <= 2; i++ {
            c += 1550
            fmt.Println(c)
        }
        c += 50 // rounded
        fmt.Printf("$%d.%02d
    ", c/10000, c%10000/100)
    }
    

    Playground: https://play.golang.org/p/YGW9SC7OcU3

    Output:

    1550
    3100
    4650
    $0.47
    
    评论

报告相同问题?

悬赏问题

  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站