---
title: "货币的一些格式化处理js"
author: "celine_q"
date: "2010-04-22T15:49:59Z"
tags: []
categories: ["Web前端"]
slug: "js"
draft: false
lastmod: "2010-04-22T15:49:59Z"
id: 650553
url: "https://celineq.iteye.com/blog/650553"
---

//计算出值 四舍五入，精确到小数点后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方法中调用

&lt;td align="center"&gt;

&lt;input type="text" name="p\_${index}" id="p\_${index}" onchange="calculate('${index}')"/&gt;

&lt;/td&gt;

&lt;td align="center"&gt;

&lt;input type="text" name="c\_${index}" id="c\_${index}" onchange="calculate('${index}')"/&gt;

&lt;/td&gt;

&lt;td align="center"&gt;

&lt;input type="text" name="a\_${index}" id="a\_${index}" onchange="calculate('${index}')"/&gt;

&lt;/td&gt;