jQuery 计算,用逗号代替点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5293264/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:55:37  来源:igfitidea点击:

Calculation, replace dot with a comma

jqueryeuro

提问by YDL

I have an order form on which I use the jQuery Calculation Plugin to sum up the total.

我有一个订单,在上面我使用 jQuery Calculation Plugin 来总结总数。

This summing up works fine, yet there is a problem with the produced 'sum'. In the sum I wish to replace any dot with a comma.

这种总结工作正常,但产生的“总和”存在问题。在总和中,我希望用逗号替换任何点。

The basis of the code is;

代码的基础是;

function ($this) {
    var sum = $this.sum();
    $("#totaal").html("€ " + sum2);
}

Using a .replace() directly on the var sum doesn't work (referenced function not available on object). I have also tried this (but without effect);

直接在 var sum 上使用 .replace() 不起作用(引用的函数在对象上不可用)。我也试过这个(但没有效果);

var sum2 = sum.toString().replace(',', '.');

As I'm kind of new to jQuery I'm pretty much stuck now, could anyone point me in the right direction?

由于我对 jQuery 有点陌生,所以我现在几乎被卡住了,有人能指出我正确的方向吗?

回答by Nathan Ostgard

Your replace line is almost right. You need to use a regexp with the goption, which says to replace all instances instead of just the first. You also have the order swapped (first is what to find, second is what to replace it with).

你的替换线几乎是正确的。您需要使用带有g选项的正则表达式,该选项表示替换所有实例,而不仅仅是第一个。您还可以交换顺序(首先是要查找的内容,其次是要替换的内容)。

var sum2 = sum.toString().replace(/\./g, ',');

Note the \before the .: .has a special meaning in a RegExp, so it has to be escaped.

注意\之前的.:.在 RegExp 中具有特殊含义,因此必须对其进行转义。

回答by Jason

If Sum was a number then this would work.

如果 Sum 是一个数字,那么这将起作用。

var sum_formatted = String( sum ).replace(/\./g,',');

Can you run typeof(sum) and tell us what the output is.

你能运行 typeof(sum) 并告诉我们输出是什么。

Also if you can set the project up in jsfiddle.com that would be great.

此外,如果您可以在 jsfiddle.com 中设置该项目,那就太好了。

回答by nzifnab

Your problem is that your replace function should read replace('.', ',')not the other way around (you had replace(',', '.')), Note that the first argument is what you're looking for, and the second argument is what you want there instead. You were replacing all commas with periods. Regex here is unnecessary.

你的问题是你的替换函数不应该反过来读replace('.', ',')(你有replace(',', '.')),注意第一个参数是你要找的,第二个参数是你想要的。您正在用句点替换所有逗号。这里的正则表达式是不必要的。