简体   繁体   中英

Rounding up to two decimal place in javascript eg 4.9995 to 4.99 in mathematical way in js

How can I convert decimal number to 2 decimal place number? Example: I want to connvert 4.995 to 4.99 but javascript is returning 5.00.

 var price=4.995; var rounded_price=price.toFixed(2); console.log(rounded_price); 

I wouldn't call it rounding but you can achieve it by:

 function trim2Dec(n) { return Math.floor(n * 100) / 100; } alert(trim2Dec(4.995)); 

您可以为此使用正则表达式,如下所示:

 alert("4.995".replace(/(\\d+(\\.\\d{1,2})?)\\d*/, "$1")) 

This is Pretty simple check out this code

 var price=4.995; var price1=4.985; var rounded_price=(Math.round(price*100)/100); var rounded_price1=(Math.round(price1*100)/100); console.log("price : "+rounded_price+" price1 : "+rounded_price1); 

here at first i am multiplying the price and then i have divided it with 100..just as we do to find the percentage of any number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM