AMIN Gholibeigian
AMIN Gholibeigian

Reputation: 337

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?

Upvotes: 15

Views: 12764

Answers (3)

Matt
Matt

Reputation: 75327

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)

Upvotes: 15

SLaks
SLaks

Reputation: 887797

Just cut the longer string:

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

Upvotes: 9

David Thomas
David Thomas

Reputation: 253416

A slightly convoluted 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 a regex to match the numbers before the decimal point and the two following that decimal point, using parseFloat() to then convert it back to a number.

References:

Upvotes: 0

Related Questions