计算,用逗号替换点
我有一个订单表格,我在其中使用 jQuery 计算插件来总结总数。
这种求和工作正常,但生成的“总和”存在问题。总之,我希望用逗号替换任何点。
该代码的基础是;
function ($this) {
var sum = $this.sum();
$("#totaal").html("€ " + sum2);
}
直接在 var sum 上使用 .replace() 不起作用(引用的函数在对象上不可用)。我也尝试过这个(但没有效果);
var sum2 = sum.toString().replace(',', '.');
由于我是 jQuery 的新手,我现在几乎陷入困境,有人能指出我正确的方向吗?
I have an order form on which I use the jQuery Calculation Plugin to sum up the total.
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的替换行几乎是正确的。您需要使用带有
g
选项的正则表达式,该选项表示替换所有实例而不是仅替换第一个实例。您还交换了顺序(第一个是要查找的内容,第二个是要替换的内容)。请注意
.
之前的\
:.
在正则表达式中具有特殊含义,因此必须对其进行转义。Your replace line is almost right. You need to use a regexp with the
g
option, 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).Note the
\
before the.
:.
has a special meaning in a RegExp, so it has to be escaped.如果 Sum 是一个数字,那么这将起作用。
你能运行 typeof(sum) 并告诉我们输出是什么吗?
另外,如果您可以在 jsfiddle.com 中设置该项目,那就太好了。
If Sum was a number then this would work.
Can you run typeof(sum) and tell us what the output is.
Also if you can set the project up in jsfiddle.com that would be great.
您的问题是您的替换函数应该读取
replace('.', ',')
而不是相反(您有replace(',', '.')
),请注意,第一个参数是您要查找的参数,第二个参数是您想要的参数。您将所有逗号替换为句点。这里的正则表达式是不必要的。Your problem is that your replace function should read
replace('.', ',')
not the other way around (you hadreplace(',', '.')
), 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.