简体   繁体   中英

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

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

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

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

Output:

1550
3100
4650
$0.47

you can try https://github.com/shopspring/decimal if you really concern about precision,

try this code:

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)

}

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

Output:

z value: 0.45
is z pass the test?  true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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