简体   繁体   English

在javascript中删除两个小数点后的数字而不是圆形数字?

[英]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? 但我不想将最后一个数字舍入为7,我该怎么办?

Use simple math instead; 使用简单的数学代替;

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

(jsFiddle) (的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) (的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. 这有效地获取变量i并将其转换为字符串,然后使用正则表达式匹配小数点前的数字和小数点后面的数字,使用parseFloat()然后将其转换回数字。

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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