ITeye博客

货币的一些格式化处理js

celine_q · 2010-04-22 15:49 · Web前端 · Markdown

//计算出值 四舍五入,精确到小数点后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>

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。