-1
 $('#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 中做到这一点?

4

2 回答 2

1

尝试这个

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

我想你想四舍五入并允许小数点后两位,

所以如果数字是 3546.699433
parseFloat(pm)*100 = 354669.9433

数学地板(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>
于 2013-07-21T06:59:27.143 回答
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。如果我是用户,我会觉得这很烦人。

于 2013-07-21T07:07:30.337 回答