Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to retain the first 2 numbers as is after the decimal point. Javascript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Jsfiidle:

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading