繁体   English   中英

我们应该如何计算金钱(十进制、大浮点数)

[英]How should we calc money (decimal, big.Float)

有人能说出在 Go 中计算财务数据的正确方法吗? 我尝试使用 big.Float 但很可能我错过了一些东西。 核心目标是计算浮点数和精度从 2 到 4 没有任何损失。 0.15 + 0.15总是应该是 0.30。 float尝试: https://play.golang.org/p/_3CXtRRNcA0 big.Float .浮动尝试: https://play.golang.org/p/zegE__Dit1O

浮点是不精确的。 使用缩放为美分或分数美分的整数 ( int64 )。


例如,美分,

package main

import (
    "fmt"
)

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

游乐场: https://play.golang.org/p/k4mJZFRUGVH

Output:

15
30
45
$0.45

例如,四舍五入的百分之一,

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\n", c/10000, c%10000/100)
}

游乐场: https://play.golang.org/p/YGW9SC7OcU3

Output:

1550
3100
4650
$0.47

如果你真的关心精度,你可以试试https://github.com/shopspring/decimal

试试这个代码:

package main

import (
    "fmt"

    "github.com/shopspring/decimal"
)

func main() {

    z := decimal.NewFromFloat(0)

    b := decimal.NewFromFloat(0.15)

    z = z.Add(b)
    z = z.Add(b)
    z = z.Add(b)

    fmt.Println("z value:", z)

    testz := z.Cmp(decimal.NewFromFloat(0.45)) == 0

    fmt.Println("is z pass the test? ", testz)

}

游乐场: https://play.golang.org/p/g_fSGlXPKDH

Output:

z value: 0.45
is z pass the test?  true

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM