jQuery - 四舍五入到小数点后两位并用该数字计算
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41165220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - Round to 2 decimal places and calculate with that number
提问by lewis4u
How to round the tax and brutto values to 2 decimal places...
如何将税和布鲁托值四舍五入到小数点后两位...
I have tried to use .toFixed(2) but that returns a string and then i can't calculate with it anymore.
我曾尝试使用 .toFixed(2) 但它返回一个字符串,然后我不能再用它计算了。
If someone could update the fiddle and make it work please?
如果有人可以更新小提琴并使其工作吗?
And try to input number 23
并尝试输入数字 23
// calculate brutto and tax
$(document).on('keyup paste', '#netto', function () {
var netto = $("#netto").val();
$("#brutto").val(netto * 1.19).toFixed(2);
var brutto = $("#brutto").val();
$("#tax").val(brutto - netto);
});
回答by Milind Anantwar
Few issues in your code:
您的代码中的几个问题:
1) You don't need event delegation unless you have elements being loaded dynamically.
1) 除非您有动态加载的元素,否则您不需要事件委托。
2) you should always parse values before doing any mathematical operations on them.
2)在对它们进行任何数学运算之前,您应该始终解析它们。
3) you are using .toFixed(2)
on jquery method which is throwing the error. toFixed
should be used with float values instead. also make sure that toFixed is used while setting both textbox values:
3) 您正在使用.toFixed(2)
抛出错误的 jquery 方法。toFixed
应该与浮点值一起使用。还要确保在设置两个文本框值时使用 toFixed:
// calculate brutto and tax
$('#netto').on('keyup paste', function () {
var netto = parseFloat($("#netto").val());
$("#brutto").val((netto * 1.19).toFixed(2));
var brutto = parseFloat($("#brutto").val());
$("#tax").val((brutto - netto).toFixed(2));
});
回答by Manoj Lodhi
Try this may be it helps you,
试试这个可能对你有帮助
$(document).on('keyup paste', '#netto', function () {
var netto = parseFloat($("#netto").val()).toFixed(2);
$("#brutto").val((netto * 1.19).toFixed(2));
var brutto = parseFloat($("#brutto").val()).toFixed(2);
$("#tax").val((brutto - netto).toFixed(2));
});
回答by Blablalux
Outside of a jQuery context, you can make good use of the following function :
在 jQuery 上下文之外,您可以充分利用以下功能:
function round(value, precision) {
var aPrecision = Math.pow(10, precision);
return Math.round(value*aPrecision)/aPrecision;
}
Here's your updated fiddle demonstrating its use : https://jsfiddle.net/yuq6kLn2/
这是您更新的小提琴演示其用途:https: //jsfiddle.net/yuq6kLn2/
回答by Stan
You'll need to use Number as the first argument inside .val()
just to be sure all your values are numbers, otherwise if at least one is not a number, you'll have a problem as I had before. See below:
您需要使用 Number 作为内部的第一个参数.val()
,以确保您的所有值都是数字,否则如果至少有一个不是数字,您就会遇到我以前遇到的问题。见下文:
$("#tax").val(Number(brutto - netto).toFixed(2));