Are there any good JavaScript currency or decimal classes?

前端 未结 7 2421
孤城傲影
孤城傲影 2021-02-19 06:57

I am trying to deal with JavaScript values such as 23.45, but I want to be able to do mathematical operations on these values (addition, subtraction, multiplication

相关标签:
7条回答
  • 2021-02-19 07:23

    Integers.

    There is no need to use floating-point for currency. Use fixed-point, where the number of decimal points is 0.

    You count in pennies (or possibly in tenths of pennies).

    0 讨论(0)
  • 2021-02-19 07:23

    New kid on the block: moneysafe. It's open-source, and uses a functional approach that allows smart composition.

    $(.1) + $(.2) === $(.3).cents;
    

    https://github.com/ericelliott/moneysafe

    0 讨论(0)
  • 2021-02-19 07:36

    Instead of using integers (which have their own problems)

    I would use the bignumber.js library

    0 讨论(0)
  • 2021-02-19 07:36

    There is Math

    The Math object is build into the JavaScript spec so every browser has it natively.

    As for data types, JavaScript has Number. That's it. We have no other number data type. The best think to do is to try and work with Integers.

    0 讨论(0)
  • 2021-02-19 07:39

    The toFixed method can round to a given number of decimals.

    There is also a Javascript sprintf implementation.

    0 讨论(0)
  • 2021-02-19 07:40

    ku4jQuery-kernel contains both a money class and a math utility that contain operations and rounding, including round, roundUp and roundDown. These are nice methods because you can pass a value to round to. For example you can do $.math.round(3.4567, -2) and it will round the number 3.4567 to the nearest 10^-2. The same goes for money. $.money(100.87).divide(2).roundUp().toString() will yield "$50.44". You can go further and add the denomination of money as a second parameter, say "B" for Bitcoin, $.money(100.87, "B").divide(2).roundUp().toString(). You can find more about this library here ku4jQuery-kernel and more libraries that you may find useful here kodmunki github. These libraries are closely maintained and used in many production projects. If you decide to try them, I hope that you find them useful! Happy coding :{)}

    0 讨论(0)
提交回复
热议问题