Home > Web Front-end > JS Tutorial > How to keep two decimal places in javascript

How to keep two decimal places in javascript

藏色散人
Release: 2019-06-18 09:10:42
Original
4468 people have browsed it

How to keep two decimal places in javascript

Below we will introduce to you the implementation method of retaining two decimal places in JavaScript:

Rounding

The following processing results will be Rounding:

var num =2.446242342;
num = num.toFixed(2);  // 输出结果为 2.45
Copy after login

No rounding

The following processing results will not be rounded.

The first one, first convert the decimal into an integer:

Math.floor(15.7784514000 * 100) / 100   // 输出结果为 15.77
Copy after login

The second one, treat it as a string, use regular matching:

Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/))   // 输出结果为 15.77,不能用于整数如 10 必须写为10.0000
Copy after login

Note: If it is a negative number, please First convert it to a positive number and then calculate it, and finally convert it back to a negative number

Recommended: "javascript video tutorial"

The above is the detailed content of How to keep two decimal places in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template