简体   繁体   中英

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?

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)

只需切断较长的字符串:

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM