简体   繁体   中英

Javascript - Prices and floats

I'm performing a number of operation on prices ie decimal numbers such as 999.99

Problem is I can't find an alternative to working with floats in JavaScript. Floats aren't perfectly accurate, and not accurate enough for pricing.

Operations include multiplications, additions, subtractions and divisions.

Usually programming languages have a fixed point decimal library, but can't find a similar one for JavaScript.

Help would be great!

Thanks :)

When working with prices or other financial data that requires precision, always work with integers, representing number of less significant units you wish to handle. At very least it should be cents (kopecks, or whatever else 1/100 fraction your currency of choice uses). Often financial system use even less units represented as integers for more precision, such as micros (for example $1.23 = 1230000 micros). This will help you avoid many problems associated with IEEE floats calculations and make sure that your precision is exactly where you want it.

JavaScript only has the Number Object.

You can use toFixed(x) where x is the number of digits after the decimal, or toPrecision(x) where x is the required length.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM