简体   繁体   English

Javascript中带逗号的数字

[英]Numbers with commas in Javascript

I have a javascript function that accepts a number and performs a mathematical operation on the number. 我有一个javascript函数接受一个数字并对数字执行数学运算。 However, the number I'm passing in could have a comma in it, and from my limited experience with Javascript I am having problems working with that value. 但是,我传入的数字可能会有逗号,而且由于我使用Javascript的经验有限,我在使用该值时遇到了问题。 It doesn't seem to treat that as a numeric type. 它似乎不把它当作数字类型。

What's the easiest way to take a parameter with a value of 1,000 and convert it to a numeric 1000? 获取值为1,000的参数并将其转换为数字1000的最简单方法是什么?

You can set up your textbox to have an onblur() function so when the user attempts to leave the textbox, you then remove the commas from the value by using the javascript replace function 您可以将文本框设置为具有onblur()函数,这样当用户尝试离开文本框时,您可以使用javascript 替换函数从值中删除逗号

example : 例如

  function checkNumeric(objName)
  {
    var lstLetters = objName;

    var lstReplace = lstLetters.replace(/\,/g,'');
  }  

With input tag here: 带输入标签:

<input type="text" onblur="checkNumeric(this);" name="nocomma" size="10" maxlength="10"/>

A quick and dirty way is to use the String.replace() method: 一种快速而肮脏的方法是使用String.replace()方法:

var rawstring = '1,200,000';
var cleanstring = rawstring.replace(/[^\d\.\-\ ]/g, '');

This will set cleanstring to: 1200000 . 这将把cleanstring设置为: 1200000 Assuming you are using US formatting, then the following conversions will occur: 假设您使用的是美国格式,则会发生以下转换:

1234 --> 1234
1,234 --> 1234
-1234 --> -1234
-1,234 --> -1234
1234.5 --> 1234.5
1,234.5 --> 1234.5
-1,234.5 --> -1234.5
1xxx234 --> 1234

If you are in other locales that invert the '.' 如果您在其他语言环境中反转'。' and ',', then you'll have to make that change in the regex. 和',',然后你必须在正则表达式中做出改变。

Converts comma delimited number string into a type number (aka type casting ) 将逗号分隔的数字字符串转换为类型编号(也称为类型转换

+"1,234".split(',').join('') // outputs 1234

Breakdown : 细分

+             - math operation which casts the type of the outcome into type Number
"1,234"       - Our string, which represents a comma delimited number
.split(',')   - split the string into an Array: ["1", "234"], between every "," character
.join('')     - joins the Array back, without any delimiter: "1234"

And a simple function would be: 一个简单的功能是:

function stringToNumber(s){
  return +s.split(',').join('');
}

Just replace all the commas with a blank. 只需用空白替换所有逗号即可。

You can follow this: http://blog.techsaints.com/2007/06/25/javascript-how-to-remove-all-commas-from-a-number/ 您可以按照以下步骤操作: http//blog.techsaints.com/2007/06/25/javascript-how-to-remove-all-commas-from-a-number/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM