jQuery,将分隔符更改为点并划分两个选定的数字 [英] jQuery, change separator to dot and divide two selected numbers

查看:52
本文介绍了jQuery,将分隔符更改为点并划分两个选定的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var result = parseFloat($('.lot2').text()) / parseFloat($('span.Price').text());
$('.result').text(result);
});

如何将选定的值从逗号分隔值转换为点分隔值?有str.replace这个函数,但是不知道怎么放到函数里.

How can I convert selected values from comma separated values to dot separated values? There is this function str.replace, but I don't know how to put it in the function.

推荐答案

如何将选定的值从逗号分隔值转换为点分隔值?

How can I convert selected values from comma separated values to dot separated values?

由此,我认为您从 $('.lot2').text()$('span.Price').text() 将使用 , 作为小数点而不是 .(在某些语言环境中就是这种情况).我假设您可能还有 . 作为其中的千位分隔符.

From that, I take it that the values you get from $('.lot2').text() and $('span.Price').text() will use , as the decimal point rather than . (as is the case in some locales). I assume that you may also have . as a thousands separator in there.

如果这就是你的意思,那么你需要做 , => . 转换,去掉 . 千位分隔符,然后解析结果,然后对结果值进行 . => , 转换(并可能添加 . 千位分隔符).为了清楚起见,这里将每个步骤分开:

If that's what you mean, then you need to do the , => . conversion, remove the . thousands separator, then parse the result, then do . => , conversion on the resulting value (and possibly add the . thousands separator). Here it is with each step separate for clarity:

// Get lot 2
var lot2 = $('.lot2').text();
// Remove all `.` thousands separators, replace the one `,` decimal separator with `.`
lot2 = lot2.replace(/\./g, '').replace(",", ".");
// Same with price
var price = $('span.Price').text().replace(/\./g, '').replace(",", ".");
// Parse them and get the result
var result = parseFloat(lot2) / parseFloat(price);
// Replace the `.` decimal separator with `,`
result = String(result).replace(".", ",");
// Show result
$('.result').text(result);

如果您想在其中添加 . 千位分隔符,这个问题及其答案(以及这里的其他几个)展示了如何做到这一点,只需使用 . 而不是 .

If you want to add . thousands separators in there, this question and its answers (and several others here on SO) show how to do that, just use . rather than ,.

由于这可能会在您的代码中重复出现,您可能希望将两个函数(语言环境形式 => JavaScript 形式,JavaScript 形式 => 语言环境形式)放入可以重用的函数中.

Since this is likely to come up repeatedly in your code, you probably want to put both functions (locale form => JavaScript form, JavaScript form => locale form) into functions you can reuse.

这篇关于jQuery,将分隔符更改为点并划分两个选定的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆