Summary: JavaScript amount calculation

Source: Internet
Author: User
Tags parse string

Today in the project to develop a calculation of the amount of functionality, I started to do this:

eg

var amount + = parsefloat (0.01+0.02);

Results: 0.0300000000000000001

Why is it?

Search the parsefloat theme:

1. The parsefloat () function---Parse string---returns a floating-point number.

During the parsing process, I encountered

plus sign (+ or-),

Numbers (0-9),

Decimal point

Index in science notation (e or E)

  other than the characters ,

It ignores the character and all subsequent characters. Whitespace characters at the top of the parameter string are ignored.

The first character cannot be parsed into a number---"returns NaN.

Well..... Feeling or understanding is not deep, why would be so a long string, precision problems, see how the principle ....

But..... Didn't find a clear explanation of the underlying

Let's take a look at the solution for a moment:

(1)

ToFixed (n) But this method is not compatible with JS version requirements IE5

(2)

var price = 5.02
var quantity = 4
var amount= math.round (parsefloat (price*100 *quantity))/100;

Math.ceil () is rounding up
Math.floor () is rounded down
Math.Round () is rounded

Welcome to provide solutions, answer doubts ....

Summary: JavaScript amount calculation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.