简体   繁体   English

Javascript中的乘法

[英]Multiplcation in Javascript

I have a script for taking data entered into a Price field on my editor and splitting it across a Pounds and Pence field based on the .我有一个脚本,用于将数据输入到我的编辑器上的价格字段中,并将其拆分为基于. symbol.象征。

Now I've been asked if I could multiply the Price field by 1.2 and display the result in the Pounds field.现在有人问我是否可以将 Price 字段乘以 1.2 并在 Pounds 字段中显示结果。 The pence field would no longer be needed.便士字段将不再需要。

I have no idea if multiplication can even work and especially using decimal points... Can anyone explain how I should rewrite the below?我不知道乘法是否可以工作,尤其是使用小数点......谁能解释我应该如何重写下面的代码?

$('#price1').keyup(function(event) {
    if ($('#price1').val().indexOf('.') != -1){
        $('#pence1').val($('#price1').val().substr($('#price1').val().indexOf('.') + 1, $('#price1').val().lengh));  
        $('#pound1').val($('#price1').val().substr(0, $('#price1').val().indexOf('.')));  
    }else{
        $('#pound1').val($('#price1').val());
    };
});

Some things to remark:有几点需要说明:

  • Your current solution has a spelling mistake for length .您当前的解决方案有length拼写错误。

  • Don't locate the decimal point.不要定位小数点。 Instead use native JavaScript capabilities to evaluate the input.而是使用本机 JavaScript 功能来评估输入。 You can use parseFloat() , Number() or the unary plus operator for that.您可以为此使用parseFloat()Number()或一元加号运算符。

  • Once you have the numeric value, you can multiply using the * operator.获得数值后,您可以使用*运算符进行乘法运算。 As multiplication will also convert its operands to number, you don't even need the previous advice, although it is still good practice to first do the conversion to number and then do the arithmetic.由于乘法也会将其操作数转换为数字,因此您甚至不需要前面的建议,尽管首先将其转换为数字然后进行算术仍然是一种很好的做法。

  • Use the input event instead of the keyup event: input is not always the result of key events (think copy/paste via context menu, drag/drop, other devices...)使用input事件而不是keyup事件:输入并不总是按键事件的结果(想想通过上下文菜单复制/粘贴、拖放、其他设备......)

Here is the proposed solution:这是建议的解决方案:

$('#price1').on("input", function(event) {
    var num = +$('#price1').val(); // convert to number using unary plus operator
    // multiply, format as string with 2 decimals, and convert back to number
    num = +(num * 1.2).toFixed(2)
    $('#pound1').val(num);  // output
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM