导航

ToFixed()用于四舍五入的问题及解决方法

Posted on 2017-02-24 15:01  JohnChou'LN  阅读(602)  评论(0)    收藏  举报

JavaScript方法:

/*
 * target Input控件
 * value 数值
 * decimal 小数位数
 */
function DetailsFormatNumber(target, value, decimal) {
    value = !isNaN(value) && value != undefined && value != "" ? parseFloat(value) : 0;
    if (parseFloat(value) < 0) value = 0;

    $(target).val(value.toFixed(decimal));
}

 Input

<input type="text" style="height:18px;" onclick="javascript:$(this).select();" onblur="javascript:DetailsFormatNumber(this,$(this).val(),4);" />

在个别情况下,四舍五入会失效,将JavaScript修改为如下方法即可

/*
 * target Input控件
 * value 数值
 * decimal 小数位数
 */
function DetailsFormatNumber(target, value, decimal) {
    value = !isNaN(value) && value != undefined && value != "" ? parseFloat(value) : 0;
    if (parseFloat(value) < 0) value = 0;

    var result = Math.round(value * Math.pow(10, decimal)) / Math.pow(10, decimal);
    $(target).val(result.toFixed(4));
    //$(target).val(value.toFixed(decimal));
}