How to intercept decimal places in JS and perform rounding

Source: Internet
Author: User

Someone asked JavaScript how to intercept decimal places and rounding them out. This is a very common JS technology. Many new users may encounter this problem, so I sorted out the post, for new users.

1. Round Method
Purpose: return the nearest integer to the given numeric expression.
Syntax: Math. Round (number). The required number parameter is the value to be rounded to the nearest integer.
Note: If the decimal part of number is greater than or equal to 0.5, the return value is the smallest integer greater than number. Otherwise, round returns the maximum integer less than or equal to number.

2. In JavaScript 1.5 (supported by ie5.5 + and ns6 +), two functions dedicated to currency circulation are added, number. tofixed (X) and number. toprecision (X ).

Number. tofixed (x) truncates the specified number to X digits after the decimal point, and number. toprecision (x) truncates the entire number to a specified length (X. Note: one is to calculate the length after the decimal point, and the other is to calculate the length of the entire number.

For example:
<SCRIPT type = "text/JavaScript">
VaR AA = 2.3362;
Document. Write (AA. tofixed (1); // 2.3
Document. Write (AA. tofixed (2); // 2.34
Document. Write (AA. toprecision (2); // 2.3
Document. Write (AA. toprecision (3); // 2.34
Document. Write (math. Round (AA * 10)/10); // 2.3
Document. Write (math. Round (AA * 100)/100); // 2.34
</SCRIPT>

Because it is a new function, you need to consider browser support issues.

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.