table替换逗号为点的价格计算

代码可以直接运行

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<table id="table01" border="1" cellpadding="0" cellspacing="1">
	<tr>
        <td class="td_num">nr</td>
		<th>1</th>
		<th>2</th>
		<th>3</th>
		<th>4</th>
	</tr>

	<tr class="tab_tr">
        <td class="td_num">1</td>
		<td>1</td>
		<td><input type="text" class="tx"></td>
		<td >
            <button>
                <a href="#" class="dao">导出</a>
            </button>
        </td>
		<td>
		</td>
	</tr>
    <tr  class="tab_tr">
        <td class="td_num">2</td>
        <td>1</td>
        <td><input type="text" class="tx"></td>
        <td >
            <button>
                <a href="#" class="dao">导出</a>
            </button>
        </td>
        <td>
        </td>
    </tr>

    <tr class="tab_tr">
        <td class="td_num">3</td>
        <td>1</td>
        <td><input type="text" class="tx"></td>
        <td >
            <button>
                <a href="#" class="dao">导出</a>
            </button>
        </td>
        <td>
        </td>
    </tr>
	
</table>
<button class="t">同步为账价格</button>
<input type="text" class="text">
<script  src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
	$(function(){

        var num = $('#table01').find('tr').eq(-3).find('.td_num').text();

        $('.t').click(function () {
            var n = 0.0;
            var val = 0.0;
            $(".tx").each(function(){
            console.log('当前框:'+$(this).val());

                if (/^[\d,]/.test($(this).val())){
                    val = parseFloat($(this).val().replace(',','.'));
                }else {
                    val = parseFloat($(this).val());
                }

                if ($(this).val().trim()!=''){
                    n = n + val;
                    console.log('val= '+val);
                }
            });
            console.log('总的n= '+toDecimal(n));
        });

        function toDecimal(x) {
            var val = Number(x)
            if(!isNaN(parseFloat(val))) {
                val = val.toFixed(2);
            }
            return  val;
        }
    });
</script>
</body>
</html>

tofixed方法是指定小数点位数; /[1]/.test($(this).val())是正则匹配到逗号,当然也可以直接用indexof来检索是否有逗号; parseFloat($(this).val().replace(',','.'));就是把逗号替换为小数点,然后转为浮点数


  1. \d, 

最后修改:2020-01-28 06:22:48
0