douzheng9221 2018-10-06 01:04
浏览 516
已采纳

Golang:如何将float64货币表示形式转换为最小面额? (乘以100并不适用于所有货币)

I'm dealing with a float64 representation of money. For example, 2.9 for usd represents $2.90, so if I need to convert this to the lowest denomination for the currency, I just multiple by 100 (2.9*100= 290 cents).

This works with most major currencies. However, in Japan, for example, the float64 representation will not have a decimal because Yen is already the lowest representation. If I get float64(290) Yen, multiplying by 100 would give an excess number of Yen if I'm trying to obtain the lowest denomination - it should stay as is.

What's the best way to handle this besides special casing when to multiply by 100 for certain currencies?

EDIT: the two pieces of information I have are the float representation and the ISO currency code.

  • 写回答

1条回答 默认 最新

  • doufeng5059 2018-10-06 02:06
    关注

    Do not use floating-point numbers for money. Floating-point numbers are an approximation. float64 (the set of all IEEE-754 64-bit floating-point numbers) conforms to the IEEE Standard for Floating-Point Arithmetic (IEEE 754).

    Wikipedia: IEEE 754


    Use the ISO 4217 standard to determine the minor currency unit exponent. It is 2 (10² = 100) for most currencies and 0 (10⁰ = 1) for the Japanese Yen (JPY).

    Wikipedia: ISO 4217

    Current currency & funds code list

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用