JavaScript代码返回十进制后的多位数

时间:2013-07-11 06:17:54

标签: javascript html

我有代码,我需要到达的数字返回十进制后的1或2位数字而不是像现在这样,这就是我所拥有的。

function GetDiff (dt) { 
    sMins = " Min";
    sHours = " Hrs";
    sDays = " Days";

    if ( Math.abs (DateDiff ("n", now, dt)) < 1440 ) {
        if ( Math.abs (DateDiff ("n", now, dt)) <= 60 ) {
            return (Math.abs (DateDiff ("n", now, dt)) + sMins);
        }
        else
        {
            return (Math.abs (DateDiff ("n", now, dt)/60) + sHours);
        }
    }
    else
    {
        return (Math.abs (DateDiff ("n", now, dt)/1440) + sDays);
    }
}

6 个答案:

答案 0 :(得分:4)

您可以使用.toFixed(2)将数字格式化为2位小数。

请注意,.toFixed()会返回一个字符串,因此如果您希望再次将结果作为数字处理,则需要parseFloat()

function GetDiff (dt) { 
    sMins = " Min";
    sHours = " Hrs";
    sDays = " Days";

    if ( Math.abs (DateDiff ("n", now, dt)) < 1440 ) {
        if ( Math.abs (DateDiff ("n", now, dt)) <= 60 ) {
            return (Math.abs (DateDiff ("n", now, dt)) + sMins).toFixed(2);
        }
        else
        {
            return (Math.abs (DateDiff ("n", now, dt)/60) + sHours).toFixed(2);
        }
    }
    else
    {
        return (Math.abs (DateDiff ("n", now, dt)/1440) + sDays).toFixed(2);
    }
}

答案 1 :(得分:1)

var num = 5.56789;
var n=num.toFixed(2);

答案 2 :(得分:1)

所以基本上你需要对值进行舍入:

function GetDiff (dt) { 
    sMins = " Min";
    sHours = " Hrs";
    sDays = " Days";

    if ( Math.abs (DateDiff ("n", now, dt)) < 1440 ) {
        if ( Math.abs (DateDiff ("n", now, dt)) <= 60 ) {
            return (Math.abs (DateDiff ("n", now, dt)) + sMins).toFixed(2);
        }
        else
        {
            return (Math.abs (DateDiff ("n", now, dt)/60) + sHours).toFixed(2);
        }
    }
    else
    {
        return (Math.abs (DateDiff ("n", now, dt)/1440) + sDays).toFixed(2);
    }
}

来源:https://stackoverflow.com/a/8927144/821056

http://www.mredkj.com/javascript/numberFormat.html

答案 3 :(得分:0)

以下是如何将数字舍入到两位小数

var original=28.453
var result=Math.round(original*100)/100  //returns 28.45

取自:http://www.javascriptkit.com/javatutors/round.shtml

答案 4 :(得分:0)

我想通了!!现在每当我输入.tofixed它都行不通,但就像我说的那样,这是稍后在脚本中的代码函数,所以idk。

                    function GetDiff (dt) { 
        sMins = " Min";
    sHours = " Hrs";
    sDays = " Days";

    if ( Math.abs (DateDiff ("n", now, dt)) < 1440 ) {
        if ( Math.abs (DateDiff ("n", now, dt)) <= 60 ) {
            return (Math.abs (DateDiff ("n", now, dt)) + sMins);
        }
        else
        {
            return ((Math.floor(Math.abs (DateDiff ("n", now, dt)/60)*10)/10) + sHours);
        }
    }
    else
    {
            return ((Math.floor(Math.abs (DateDiff ("n", now, dt)/1440)*10)/10) + sDays);
    }
}

答案 5 :(得分:-1)

使用DecimalFormatter:

double number = 0.9999999999999;
DecimalFormat numberFormat = new DecimalFormat("#.00");
System.out.println(numberFormat.format(number));

会给你“0.99”。您可以在右侧添加或减去0以获得更多或更少的小数。

或者使用右侧的“#”使附加数字可选,如#,##(0.30)将尾随0变为(0.3)。