Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete digits after two decimal point not round number in javascript?

I have this :

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

output :

4.57

But i don't want to round the last number to 7 , what can i do?

like image 533
AMIN Gholibeigian Avatar asked Apr 19 '12 13:04

AMIN Gholibeigian


People also ask

How do you round off numbers after the decimal point in JavaScript?

JavaScript Number toFixed() The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals.

How can I remove the decimal part from JavaScript number?

Trunc() method. The Math. trunc() is the most popular method to remove the decimal part of JavaScript. It takes positive, negative, or float numbers as an input and returns the integer part after removing the decimal part.


1 Answers

Use simple math instead;

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

(jsFiddle)

You can stick 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)

like image 137
Matt Avatar answered Sep 30 '22 14:09

Matt