Math.floor()和parseFloat()冲突?

时间:2013-07-21 06:56:45

标签: javascript rounding parsefloat

 $('#pm').val(Math.floor(parseFloat(pm*100/100)));

完整代码:

<script type="text/javascript">     
        function updatePay() {
            // Grab all the value just incase they're needed.
            var current_price = <?php echo json_encode($current_price); ?>;
            var pm = $('#pm').val();
            var gg = pm/current_price;

            // Set the new input values.
           $('#pm').val(Math.floor(parseFloat(pm*100/100)));
            $('#gg').val(gg);
        }

        $('#pm').keyup(updatePay);
        $('#gg').keyup(updatePay);

    </script>

当我使用Math.floor时,它不允许我输入第二个小数。

我需要我的代码才能填写第二个小数位,我该如何在Javascript中执行此操作?

2 个答案:

答案 0 :(得分:1)

试试这个

$('#pm').val((Math.floor(parseFloat(pm)*100)/100).toFixed(2));

我认为你要向下舍入并允许2位小数,

所以如果号码是3546.699433
parseFloat(pm)* 100 = 354669.9433

math.floor(354669.9433)= 354669

354669/100 = 3546.69

<script type="text/javascript">     
        function updatePay() {
            // Grab all the value just incase they're needed.
            var current_price = <?php echo json_encode($current_price); ?>;
            var pm = $('#pm').val();
            var gg = pm/current_price;

            // Set the new input values.
            $('#pm').val((Math.floor(parseFloat(pm)*100)/100).toFixed(2));
            $('#gg').val(gg);
        }

        $('#pm').change(updatePay);
        $('#gg').chnage(updatePay);

    </script>

如果你想要在keyup上更新的东西,请尝试沿着这些方向进行更新

Javascript:

   document.getElementById("num1").onkeyup = function(){
        var val = (Math.floor(parseFloat( document.getElementById("num1").value)*100)/100).toFixed(2);
        if(isNaN(val)){
            document.getElementById("result").innerHTML = "pm will appear here";
        }
        else if(val){
            document.getElementById("result").innerHTML = val;
        } else {
            document.getElementById("result").innerHTML = "pm will appear here";
        }


    }

HTML:

<body>
    <input type="button" id="myButton" value="click me"/>
    <span id="result"></span>
    <input type="text" id="num1" value="1.1111"></div>

</body>

答案 1 :(得分:0)

很难说出你想要达到的目标,但我猜想你希望pmgg中显示的值有两位数的小数精度。如果是这样的话:

function updatePay() {
    // Grab all the value just incase they're needed.
    var current_price = <?php echo json_encode($current_price); ?>;
    var pm = parseFloat($('#pm').val()); // Parse here
    var gg = pm/current_price;

    // Set the new input values.
    $('#pm').val(pm.toFixed(2));         // Round to two places and turn back into text
    $('#gg').val(gg.toFixed(2));         // " " " " " " " " "
}

附注:您已将此设置为keyup元素上的gg处理程序,但您始终会覆盖gg元素所包含的内容,而不使用其中的值gg一点都没有。如果我是一名用户,我会发现这很令人恼火。