Delete digits after two decimal point, not numbers in javascript?

I have it:

i=4.568; document.write(i.toFixed(2)); 

output:

 4.57 

But I do not want to round the last number to 7, what can I do?

+7
source share
3 answers

Use simple math instead;

 document.write(Math.floor(i * 100) / 100); 

(jsFiddle)

You can use it in your own function for reuse;

 function myToFixed(i, digits) { var pow = Math.pow(10, digits); return Math.floor(i * pow) / pow; } document.write(myToFixed(i, 2)); 

(jsFiddle)

+9
source

Just cut a longer line:

 i.toFixed(3).replace(/\.(\d\d)\d?$/, '.$1') 
+5
source

A bit confusing approach:

 var i=4.568, iToString = ​i + ''; i = parseFloat(iToString.match(/\d+\.\d{2}/)); console.log(i); 

This effectively takes the variable i and converts it to a string, and then uses the regular expression to match the numbers before the decimal point and the next two decimal points, using parseFloat() to then convert it to a number.

Literature:

0
source

All Articles