在javascript中将字符串转换为整数或浮点数 [英] Convert string to either integer or float in javascript

查看:111
本文介绍了在javascript中将字符串转换为整数或浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我不知道变量是整数型还是十进制型,是否有一种简单的方法将字符串解析为整数或浮点型?

Is there a straightforward way to parse a string to either integer or float if I don't know if the variable is integer-number-like or decimal-number-like?

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

看来我的问题缺少必要的上下文:我想做一些计算而又不丢失原始格式(原始格式表示整数与浮点数.我不在乎原始的小数位数):

It seems my question lacked the necessary context: I want to do some calculations without losing the original format (Original format thereby means integer vs. float. I don't care about the original number of decimal places):

示例:

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')

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").

If the input was 2.0 instead, the wanted result would be '3.0' (not '3').

推荐答案

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

That's how I finally solved it. I didn't find any other solution than to add the variable type to the variable ...

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>");

这篇关于在javascript中将字符串转换为整数或浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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