0

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);

3 Answers3

4

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));
user2832344
  • 264
  • 2
  • 7
0

You can use regex for this as the following:

alert("4.995".replace(/(\d+(\.\d{1,2})?)\d*/, "$1"))
Ghasan غسان
  • 5,577
  • 4
  • 33
  • 44
  • 1
    To (mis)Quote: "If you have a problem, and RegEx is your answer - you now have two problems". ;o) – allnodcoms Jan 15 '17 at 15:41
  • @allnodcoms If you find yourself having to invent the wheel each time you program, then know you are using JavaScript. In any proper language, this method will be supported by a standard library specification. However, in JavaScript, everyone does what they think is best. – Ghasan غسان Jan 15 '17 at 15:56
  • The number of ways to solve a problem in javascript = n + 1, where n = The number of ways to solve a problem in javascript... – allnodcoms Jan 15 '17 at 16:03
0

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.

  • This is very wrong. If you have a number like `4.015`, then you will get `4`! – Ghasan غسان Jan 15 '17 at 16:03
  • corrected..If you remove that -1 then the code will work fine..but you can not get exact result of 4.991 to 0.999 that will give you a result of 5 becuase its basically crossed the range – Arnab Biswas Jan 15 '17 at 16:18