am2*_*429 2 javascript parsefloat parseint
如果我不知道变量是整数数字还是十进制数字,是否有一种简单的方法将字符串解析为整数或浮点数?
a = '2'; // => parse to integer
b = '2.1'; // => parse to float
c = '2.0'; // => parse to float
d = 'text'; // => don't parse
Run Code Online (Sandbox Code Playgroud)
编辑:似乎我的问题缺乏必要的上下文:我想做一些计算而不会丢失原始格式(原始格式因此意味着整数与浮点数.我不关心原始的小数位数):
例:
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').
raj*_*uGT 12
将数字数据与1相乘的字符串.您将获得数字数据值.
var int_value = "string" * 1;
Run Code Online (Sandbox Code Playgroud)
在你的情况下
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
Run Code Online (Sandbox Code Playgroud)
对于最后一个,你将获得NaN价值.手动处理NaN值
我最终就是这样解决的。除了将变量类型添加到变量之外,我没有找到任何其他解决方案......
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>");Run Code Online (Sandbox Code Playgroud)