繁体   English   中英

在javascript中将字符串转换为整数或浮点数

[英]Convert string to either integer or float in javascript

如果我不知道变量是类似整数还是类似小数,是否有一种直接的方法可以将字符串解析为整数或浮点数?

a = '2'; // => parse to integer
b = '2.1'; // => parse to float
c = '2.0'; // => parse to float
d = 'text'; // => don't parse

编辑:似乎我的问题缺乏必要的上下文:我想在不丢失原始格式的情况下进行一些计算(原始格式因此表示整数与浮点数。我不关心原始小数位数):

例子:

String containing the formatted number ('2') => parse to number (2.0) => do some calculations (2.0 + 1 = 3.0) => restore "original format" ('3' and not '3.0')

如果输入是 2.0,则想要的结果将是“3.0”(而不是“3”)。

将具有数字数据的字符串乘以 1。您将获得数字数据值。

var int_value = "string" * 1;

在你的情况下

a = '2' * 1; // => parse to integer
b = '2.1' * 1; // => parse to float
c = '2.0' * 1; // => parse to float
d = 'text' * 1; // => don't parse    //NaN value

对于最后一个,您将获得NaN值。 手动处理 NaN 值

只需将其包装在Number()

Number('123') === 123

Number('-123.456') === -123.456

我就是这样最终解决的。 除了将变量类型添加到变量之外,我没有找到任何其他解决方案......

 var obj = { a: '2', b: '2.1', c: '2.0', d: 'text' }; // Explicitly remember the variable type for (key in obj) { var value = obj[key], type; if ( isNaN(value) || value === "" ) { type = "string"; } else { if (value.indexOf(".") === -1) { type = "integer"; } else { type = "float"; } value = +value; // Convert string to number } obj[key] = { value: value, type: type }; } document.write("<pre>" + JSON.stringify(obj, 0, 4) + "</pre>");

您可以使用:

function parse(x){
  return x==x*1?x*1:x
 }

 function parse(x){ return x==x*1?x*1:x } console.log(parse(1),typeof parse(1)) console.log(parse("1"),typeof parse("1")) console.log(parse("1.1"),typeof parse("1.1")) console.log(parse("1A"),typeof parse("1A"))

暂无
暂无

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

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