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
我们应该如何计算货币(十进制,大浮点数)
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
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
解决 无用评论 打赏 举报