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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?