15

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?

3
  • When you're working with binary floating point, things like this can happen. Commented Apr 19, 2012 at 13:56
  • @Pointy: No; he just doesn't want rounding. Commented Apr 19, 2012 at 13:58
  • Yes, but my point is that in general when dealing with floating point you can't guarantee that a constant you type in will end up being what you think it is, rounding or no rounding, primarily because 2 and 5 are relatively prime :-) Commented Apr 19, 2012 at 14:00

3 Answers 3

15

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)

Sign up to request clarification or add additional context in comments.

3 Comments

The function returns nothing ..!
should be : document.write(Math.floor(i * 100)/ 100);
This is not a correct method due to floating point number precision problem. Ex: try 0.29, you will get 0.28 instead
9

Just cut the longer string:

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

1 Comment

toFixed is a shorter solution which does its job.
0

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.