当前位置:网站首页>JS takes two decimal places

JS takes two decimal places

2022-06-23 20:34:00 It workers

We need to keep two decimal places , have access to toFixed Method , But some numbers are Unwanted With two decimal places .

For example, the following two variables

/**
*  Rhinoceros front tribe 
*/
var a = 1.777;
var b = 1.6;

Variable a The decimal point of exceeds 2 position , We can use toFixed To achieve .

a.toFixed(2); // Output 1.78

But variables b There is only one digit after the decimal point , We may not need to implement two decimal places , If you use toFixed There will be Ambiguity , for example :

b.toFixed(2);// Output 1.70

terms of settlement

We can use some mathematical skills , For example, the following implementation method :

Math.round( Variable *100)/100;

Take the example above , Execute the above formula , Will return the result we want :

/**
*  Rhinoceros front tribe 
*/
var a = 1.777;
var b = 1.6;
Math.round(a*100)/100; //1.78
Math.round(b*100)/100; //1.6

Above we have realized the method of keeping two decimal places , I hope I can sum up the way , It works for you .

原网站

版权声明
本文为[It workers]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/202112300907005965.html