go - 我们应该如何计算钱(小数,big.Float)

标签 go

有人能告诉我在 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/

相关文章:

Git2Go 获取或硬 pull

http - Golang 发送 http 请求发送两次而不是一次

Golang : Installation directory error?

go - 构建Android时在golang中读取Makefile变量

go - golang 中的 TCPListener : error when number of connections is above 60/260

go - 如何等待回调函数返回?

go - 使用 Google Cloud Platform 服务帐号查询 GSuite Directory API

go - 实现一个通用的参数方法

go - 在 Go 中反转 slice 顺序的惯用方法(不是降序排序)?

go - 使用 header 作为 application/json 在 Golang 中获取 POST 参数