Home > Web Front-end > Front-end Q&A > How to implement division with two decimal places in javascript

How to implement division with two decimal places in javascript

青灯夜游
Release: 2022-02-21 18:36:03
Original
15720 people have browsed it

Implementation method: 1. Use the "/" operator to perform division operation, the syntax is "value 1 / value 2"; 2. Use "result of division operation.toFixed(2)" or "Math.floor( The result of the division operation *100)/100" statement to retain two decimal places.

How to implement division with two decimal places in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript implements division with two decimal places

can be divided into two parts:

  • Divide two numbers: You can use the "/" operator to perform division operations

  • Retain two decimal places

General In terms of retaining two decimal places, you can use the following three methods:

1. Directly use the method toFixed(n) that comes with the numeric type, where the parameter is the number of digits that need to be retained. This The result of the conversion is character type.

var a=10;
var b=3;
var c=a/b;
console.log("两数相除的结果:"+c);
console.log("保留两位小数:"+c.toFixed(2));
Copy after login

How to implement division with two decimal places in javascript

#2. Combined with Math.floor(), use the method of multiplying first and then dividing. For example, if you want to keep two decimal places, Math.floor(c*100)/100 , if you want to keep three decimal places, then it is Math.floor(c*1000)/1000.

var a=10;
var b=3;
var c=a/b;
console.log("两数相除的结果:"+c);
console.log("保留两位小数:"+Math.floor(c*100)/100);
console.log("保留三位小数:"+Math.floor(c*1000)/1000);
Copy after login

How to implement division with two decimal places in javascript

Using this method of multiplying first and then dividing is the most common method.

3. Use regular expressions to intercept. Here you need to test your regular skills.

var a=10;
var b=3;
var c=a/b;
console.log("两数相除的结果:"+c);
console.log("保留两位小数:"+c.toString().match(new RegExp(/^\d+(?:\.\d{0,2})?/)));
Copy after login

How to implement division with two decimal places in javascript

【Related recommendations: javascript learning tutorial

The above is the detailed content of How to implement division with 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