有人能告诉我在 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)
}
Playground :https://play.golang.org/p/k4mJZFRUGVH
输出:
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)
}
Playground :https://play.golang.org/p/YGW9SC7OcU3
输出:
1550
3100
4650
$0.47
关于go - 我们应该如何计算钱(小数,big.Float),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58088633/