[英]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.