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

11,331

Solution 1

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)

Solution 2

Just cut the longer string:

i.toFixed(3).replace(/\.(\d\d)\d?$/, '.$1')
Share:
11,331

Related videos on Youtube

AMIN Gholibeigian
Author by

AMIN Gholibeigian

I am a Flash developer who knows PHP.

Updated on June 05, 2022

Comments

  • AMIN Gholibeigian
    AMIN Gholibeigian almost 2 years

    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?

  • AMIN Gholibeigian
    AMIN Gholibeigian about 12 years
    The function returns nothing ..!
  • AMIN Gholibeigian
    AMIN Gholibeigian about 12 years
    should be : document.write(Math.floor(i * 100)/ 100);
  • Angry 84
    Angry 84 over 7 years
    toFixed is a shorter solution which does its job.
  • Steven.Chang
    Steven.Chang over 2 years
    This is not a correct method due to floating point number precision problem. Ex: try 0.29, you will get 0.28 instead