shiva
shiva

Reputation: 764

Calculating prices in JavaScript

I have some energy readings that are fractional numbers like: 167512562.211221.

I need to convert these numbers into an invoice price using a kWh price value.

But Number in JavaScript is floating point and unsuitable for monetary calculations.

How should I do this?

Upvotes: 0

Views: 2072

Answers (2)

rh16
rh16

Reputation: 1073

One solution you could try is storing your numbers as the smallest division of the currency you are working in (e.g if you're dealing in dollars, store you values as cents so $1.00 becomes 100 and $5.45 becomes 545.

You will need to round your numbers after calculating from the fractional reading, using round, ceil or floor depending on what is appropriate for your business logic, but after that, things like additions and subtractions can be carried out without worrying about the downsides of floating point.

If you need to apply further fractional logic (percentage discount etc) the values can simply be rounded using the appropriate function after the calculation is applied.

Upvotes: 2

David
David

Reputation: 1246

Use a library.

There are many and this page will help you along with the things you need to know about working with money in JavasScript.

https://frontstuff.io/how-to-handle-monetary-values-in-javascript

Upvotes: 1

Related Questions