我们应该如何计算货币(十进制,大浮点数) [英] How should we calc money (decimal, big.Float)

查看:41
本文介绍了我们应该如何计算货币(十进制,大浮点数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉正确的方法来计算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 )缩放为美分或分数美分.


例如,美分

 程序包主要进口 ("fmt")func main(){美分:= int64(0)对于我:= 0;我< = 2;我++ {美分+ = 15fmt.Println(cents)}fmt.Printf("$%d.%02d \ n",cents/100,cents%100)} 

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

输出:

  153045$ 0.45 


例如,四分之一角四舍五入,

 程序包主要导入"fmt"func main(){c:= int64(0)//百分之一分对于我:= 0;我< = 2;我++ {c + = 1550fmt.Println(c)}c + = 50//取整fmt.Printf("$%d.%02d \ n",c/10000,c%10000/100)} 

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

输出:

  155031004650$ 0.47 

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

这篇关于我们应该如何计算货币(十进制,大浮点数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆