Math.floor() and parseFloat() clash?


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

试试这个

$('#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>

很难说你想实现什么,但猜测我怀疑你希望以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));         // " " " " " " " " "
}

旁注:您将此设置为gg元素上的keyup处理程序,但您始终会覆盖 gg 元素中的内容,而根本不使用 gg 中的值。如果我是用户,我会觉得这很烦人。

最新更新