如何从浮点数截断额外的零

时间:2017-06-15 19:57:02

标签: javascript floating-point

说:     var x = 6.450000000000003;     var y = 5.234500000000002;

这些是浮点除法的结果,因此需要删除3和2。如果它们具有不同的精度水平,我如何将x修剪到6.45和y到5.2345?

3 个答案:

答案 0 :(得分:0)

您可以使用Number#toFixed并将字符串转换回数字。



var x = 6.450000000000003,
    y = 5.234500000000002;
    
x = +x.toFixed(5);
y = +y.toFixed(5);

console.log(x);
console.log(y);




答案 1 :(得分:0)

您可以使用count,但必须选择精确度。

(否则,你正在失去优点,你不想要那样!)



Math.round




答案 2 :(得分:-1)

试试这个功能。如果您正如您所说,只是想要删除结束数字并删除尾随零,则以下代码可能有所帮助。



    function stripZeroes(x){
        // remove the last digit, that you know isn't relevant to what 
        // you are working on
        x = x.toString().substring(0,x.toString().length-1); 
        // parse the (now) String back to a float. This has the added 
        // effect of removing trailing zeroes.
        return parseFloat(x);}

    // set up vars for testing the above function
    var x = 6.450000000000003;
    var y = 5.234500000000002;
    
    // test function and show output
    console.log(stripZeroes(x));
    console.log(stripZeroes(y));