javascript parseFloat '500,000'当我需要 500000 时返回 500

发布于 2024-09-08 08:45:44 字数 83 浏览 5 评论 0原文

这会是处理这个问题的好方法吗?

我已经考虑过删除逗号然后解析为浮动。

你知道更好/更干净的方法吗?

谢谢

How would it be a nice way of handling this?

I already thought on removing the comma and then parsing to float.

Do you know a better/cleaner way?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

左耳近心 2024-09-15 08:45:44
parseFloat( theString.replace(/,/g,'') );
parseFloat( theString.replace(/,/g,'') );
煮茶煮酒煮时光 2024-09-15 08:45:44

我不知道为什么没有人建议这个表达式 -

parseFloat( theString.replace(/[^\d\.]/g,'') );

删除除句点之外的所有非数字字符。您也不需要为此自定义函数/循环,这太过分了。

I don't know why no one has suggested this expression-

parseFloat( theString.replace(/[^\d\.]/g,'') );

Removes any non-numeric characters except for periods. You don't need custom functions/loops for this either, that's just overkill.

讽刺将军 2024-09-15 08:45:44

没有。删除逗号。

Nope. Remove the comma.

猫弦 2024-09-15 08:45:44

您可以使用字符串替换方法,但不能使用正则表达式允许的单行替换方法。

while(str.indexOf(',')!=-1)str= str.replace(',','');
parseFloat(str);

或者要在没有 regexp= 的情况下创建单个表达式,

return parseFloat(str.split(',').join(''));

我将使用 regexp.

You can use the string replace method, but not in a one liner as a regexp allows.

while(str.indexOf(',')!=-1)str= str.replace(',','');
parseFloat(str);

Or to make a single expression without a regexp=

return parseFloat(str.split(',').join(''));

I'd use the regexp.

暖风昔人 2024-09-15 08:45:44

我没有足够的声誉来添加评论,但对于任何想知道正则表达式与 split/join 的性能的人,这里有一个快速小提琴: https://jsfiddle.net/uh3mmgru/

var test = "1,123,214.19";

var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
    var a = parseFloat(test.replace(/,/g,''));
}
var t1 = performance.now();
document.write('Regex took: ' + (t1 - t0) + ' ms');
document.write('<br>')

var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
    var b = parseFloat(test.split(',').join(''));
}
var t1 = performance.now();
document.write('Split/join took: ' + (t1 - t0) + ' ms');

我得到的结果是(每个循环 100 万次):

正则表达式:263.335 ms
拆分/连接:1035.875 ms

所以我认为可以肯定地说正则表达式是这种情况下的最佳选择

I don't have enough reputation to add a comment, but for anyone wondering on the performance for regex vs split/join, here's a quick fiddle: https://jsfiddle.net/uh3mmgru/

var test = "1,123,214.19";

var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
    var a = parseFloat(test.replace(/,/g,''));
}
var t1 = performance.now();
document.write('Regex took: ' + (t1 - t0) + ' ms');
document.write('<br>')

var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
    var b = parseFloat(test.split(',').join(''));
}
var t1 = performance.now();
document.write('Split/join took: ' + (t1 - t0) + ' ms');

The results I get are (for 1 million loops each):

Regex: 263.335 ms
Split/join: 1035.875 ms

So I think its safe to say that regex is the way to go in this scenario

错々过的事 2024-09-15 08:45:44

基于@kennebec 的想法,如果您想确保逗号正确,并且不想替换逗号,您可以尝试这样的操作:

function myParse(num) {
  var n2 = num.split(",")
  out = 0
  for(var i = 0; i < n2.length; i++) {
    out *= 1000;
    out += parseFloat(n2[i])
  }
  return out
}
alert(myParse("1,432,85"));
// Returns 1432085, as the comma is misplaced.

它可能不会那么快,但您想要替代方案:)

Building on the idea from @kennebec, if you want to make sure that the commas are correct, and you don't want to replace commas, you could try something like this:

function myParse(num) {
  var n2 = num.split(",")
  out = 0
  for(var i = 0; i < n2.length; i++) {
    out *= 1000;
    out += parseFloat(n2[i])
  }
  return out
}
alert(myParse("1,432,85"));
// Returns 1432085, as the comma is misplaced.

It may not be as fast, but you wanted alternatives :)

安人多梦 2024-09-15 08:45:44

用一个简单的函数来解决大多数常见问题怎么样?

function getValue(obj) {
  Value = parseFloat( $(obj).val().replace(/,/g,'') ).toFixed(2);
  return +Value;
}

上面的函数从字段获取值(使用 jQuery),假设输入的值是数字(我宁愿在用户输入数据时验证字段,所以我确定字段内容是数字)。

对于浮点值,如果字段中格式正确,该函数将正确返回浮点值。

此功能还远未完成,但它可以快速修复输入为 1,234.56 或 1,234,567 的值的“,”(逗号)问题。只要内容是数字,它将返回有效的数字。

返回中变量Value前面的+加号)符号命令是 JavaScript 中使用的“肮脏技巧”,用于确保返回的变量内容为数字。

很容易将该函数修改为其他目的,例如(例如)将字符串转换为数值,并解决“,”(逗号)问题

function parseValue(str) {
  Value = parseFloat( str.replace(/,/g,'') ).toFixed(2);
  return +Value;
}

:操作甚至可以组合在一个函数中。即:

function parseNumber(item,isField=false) {
  Value = (isField) ? parseFloat( $(item).val().replace(/,/g,'') ).toFixed(2) : parseFloat( item.replace(/,/g,'') ).toFixed(2)
  return +Value;
}

在这种情况下,如果调用函数 result = parseNumber('12,092.98'); 它将解析该值,因为它是一个字符串。但如果调用 result = parseNumber('#MyField', true); ,它将尝试从 '#MyField' 获取值。

正如我之前所说,这样的功能还远未完成,还可以通过多种方式进行扩展。一个想法是检查给定参数(字符串)的第一个字符,并根据字符串格式决定从哪里获取要解析的值(如果第一个字符是 = '#' 那么它是一个来自 DOM 对象的 ID,否则,如果它以数字开头,则它必须是要解析的字符串)。

尝试一下...编码愉快。

What about a simple function to solve most of the common problems?

function getValue(obj) {
  Value = parseFloat( $(obj).val().replace(/,/g,'') ).toFixed(2);
  return +Value;
}

The above function gets values from fields (using jQuery) assuming the entered values are numeric (I rather validate fields while user is entering data, so I know for sure field content is numeric).

In case of floating point values, if well formatted in the field, the function will return a float point value correctly.

This function is far from complete, but it quickly fix the "," (comma) issue for values entered as 1,234.56 or 1,234,567. It will return valid number as far the content is numeric.

The + (plus) sign in front of the variable Value in the return command is a "dirty trick" used in JavaScript to assure the variable content returned will be numeric.

it is easy to modify the function to other purposes, such as (for instance), convert strings to numeric values taking care of the "," (comma) issue:

function parseValue(str) {
  Value = parseFloat( str.replace(/,/g,'') ).toFixed(2);
  return +Value;
}

Both operations can even be combined in one function. I.e.:

function parseNumber(item,isField=false) {
  Value = (isField) ? parseFloat( $(item).val().replace(/,/g,'') ).toFixed(2) : parseFloat( item.replace(/,/g,'') ).toFixed(2)
  return +Value;
}

In such case, if function is called result = parseNumber('12,092.98'); it will parse the value as it is a String. But if called as result = parseNumber('#MyField', true); it will try to obtain the value from '#MyField'.

As I said before, such functions are far from complete, and can be expanded in many ways. One idea is to check the first character of the given parameter (string) and decide based on the string format where to obtain the value to be parsed (if 1st character is = '#' then it is an ID from a DOM object, otherwise, if it begins with a number, it must be a string to be parsed).

Try it... Happy coding.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文