-1

I would like to format my numbers to always display 2 decimal places. lets say: I have a number => 21.268998 , the o/p I'm looking is to chop the rest of the decimal point and keep only the first 2 i.e:

21.26

however with the tofixed or toPrecision approach to always rounds to a certain decimal which is causing issues when a number is 99.999999, it rounds to 100.000 which is not right.

var num1 = "1";
document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2); // this is showing correctly

var num2 = "99.99999";
document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);// this is incorrect=> I want to show 99.99

any idea how to get the first numbers to show always without rounding them off to the next number.

Jsfiidle:

https://jsfiddle.net/8ohvyczg/1/

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
user1234
  • 3,000
  • 4
  • 50
  • 102
  • 3
    There are many results in google for problems like this, did you try other approaches? Does this answer your question? [Truncate (not round off) decimal numbers in javascript](https://stackoverflow.com/questions/4912788/truncate-not-round-off-decimal-numbers-in-javascript) – Andy Ray Dec 10 '21 at 20:43
  • Multiply by 100, round down, then divide by 100. – Barmar Dec 10 '21 at 20:50

4 Answers4

2

You can use slice method in javascript:

var num2 = 99.99999;
num2 = num2.slice(0, (num2.indexOf("."))+3); 
document.getElementById('num2').innerHTML = num2;
Mana S
  • 509
  • 2
  • 6
1

Here's an approach of a simple truncate, and not round off:

var number = 26.4363
var str = number.toString();
console.log(str.substring(0, str.indexOf(".")+3));
Deepak
  • 2,660
  • 2
  • 8
  • 23
1

Did u tried Math.trunc()?

var num = "99.99999";

var round=(Math.round(num * 100) / 100).toFixed(2)
var trunc=(Math.trunc(num * 100) / 100)
console.log(round);
console.log(trunc);
Abelucho
  • 220
  • 1
  • 9
0

Many ways to do that. But you can write a custom function to do that. I use split and substring.

const num = "99.91999";

function parseNumber(num)
{
    arr = num.split('.');
    return arr[0] + '.' + arr[1].substring(0,2);
}

console.log(parseNumber(num))
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79