`
celine_q
  • 浏览: 16207 次
  • 性别: Icon_minigender_2
  • 来自: 上海
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

货币的一些格式化处理js

阅读更多

//计算出值 四舍五入,精确到小数点后2

function formatPrice(src, pos){

   return Math.round(src*Math.pow(10, pos))/Math.pow(10, pos);

}

//保留n位小数

function formatNum(num,n){

    num = String(num.toFixed(n));

    var re = /(\d+)(\d{3})/;

    return num.replace(re,"$1,$2");

}

//转换成字符串

function all(per,count){

    return per*count;

}

 

// 当计算单价×数量并将结果显示在总价input

 

/**

 * index 为索引值

 * p_ 为单价属性id的命名空间

 * c_ 为数量属性id的命名空间

 * a_ 为总价属性id的命名空间

 */

function calculate(index){

    var pricePer = document.getElementById('p_'+index).value;

    var count = document.getElementById('c_'+index).value;

    var sumPrice = document.getElementById('a_'+index);

    var val = /^\d+(\.\d+)?$/;

    if(!val.test(pricePer)){

       alert('参考单价必须为数字且非负数!');

       document.getElementById('p_'+index).value="";

       document.getElementById('a_'+index).value="";

       document.all.item('p_' + index).focus();

    }

    if(!val.test(count)){

           alert('数量必须为数字且非负数!');

           document.getElementById('c_'+index).value="";

           document.getElementById('a_'+index).value="";

           document.all.item('c_' + index).focus();

       }                  

    if(val.test(pricePer)&&val.test(count))

          // 货币显示格式

          // 字符串格式,方便后台解析成数组

          sumPrice.value = formatNum(all(formatPrice(pricePer,2),count),2);

 

}

 

最后在所有input 的onchange方法中调用

<td align="center">

<input type="text" name="p_${index}" id="p_${index}" onchange="calculate('${index}')"/>

</td>

<td align="center">

<input type="text" name="c_${index}" id="c_${index}" onchange="calculate('${index}')"/>

</td>

<td align="center">

<input type="text" name="a_${index}" id="a_${index}" onchange="calculate('${index}')"/>

</td>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics