电脑爱好者,提供IT资讯信息及各类编程知识文章介绍,欢迎大家来本站学习电脑知识。 最近更新 | 联系我们 RSS订阅本站最新文章
电脑爱好者
站内搜索: 
当前位置:首页>> Javascript>>JavaScript如何将字符串转换成数值(整数or浮点数):

JavaScript如何将字符串转换成数值(整数or浮点数)

来源:网络 | 2007-1-28 | (有13120人读过)

从input中取出的value字符串进行加减乘除操作时需要首先进行数值转换,比如:

var height = 20;
var addvalue = document.formname.addheight.value;
var newheight = height+addvalue;

如果在addheight中输入的值为13,则计算出来的newheight为2013,而我们期望的值为33,所以需要将字符串转化成数值,可以采用的方法是parseInt

上面的代码转换成如下内容就可以了:

var newheight = height+parseInt(addvalue);

如果带有小数的话,则需要采用方法parseFloat,否则小数将被忽略。

parseInt方法介绍摘抄如下:

The parseInt() function parses a string and returns an integer.

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with "0x", the radix is 16 (hexadecimal)
  • If the string begins with "0", the radix is 8 (octal). This feature is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)

parseInt(string, radix)

  • string   Required. The string to be parsed
  • radix    Optional. A number (from 2 to 36) that represents the numeral system to be used
Javascript热门文章排行
网站赞助商
购买此位置

 

关于我们 | 网站地图 | 文档一览 | 友情链接| 联系我们

Copyright © 2003-2024 电脑爱好者 版权所有 备案号:鲁ICP备09059398号