码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-02-24 15:52:44      阅读:1231      评论:0      收藏:0      [点我收藏+]

标签:isnan   cli   nan   amp   mat   value   math   input   数值   

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));
}

 

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

标签:isnan   cli   nan   amp   mat   value   math   input   数值   

原文地址:http://www.cnblogs.com/johnchou/p/6438601.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!