Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle currency in JavaScript?

Tags:

javascript

From what I have read, numbers in JavaScript are actually stored as floating points and there is no real integer type. Is this accurate?

If there is no integer type, then how can I accurately store currencies? As a string or something?

like image 731
timbram Avatar asked Apr 13 '15 17:04

timbram


People also ask

How to handle monetary values in JavaScript?

How to do this? We have to add two values 0.2 and 0.1, if we do it directly with JS we already know that there will be problems. 1) Multiply each value by 100: (0.2 * 100 + 0.1 * 100) = 30 cents. 2) Recover the value to money: (0.2 * 100 + 0.1 * 100) / 100 = 0.3.

What is js currency?

currency. js is a lightweight ~1kb javascript library for working with currency values. It was built to work around floating point issues in javascript. This talk by Bartek Szopka explains in detail why javascript has floating point issues.


1 Answers

[...] and there is no real integer type. Is this accurate?

Yes.

If there is no integer type, then how can I accurately store currencies?

You can still use values that we would consider as integers, i.e. 5, 42, etc. Those values are accurate. "Integer" values only lose precision if they are > 2^53.

What you should avoid, in any language, is using rational numbers to represent currency, if you perform any computation with it. Meaning, instead of 4.13, you should use 413.

See Why not use Double or Float to represent currency?

like image 70
Felix Kling Avatar answered Sep 27 '22 21:09

Felix Kling