【JavaScript】判断指定字符串是否为有效数字

最近在做一个ColdFusion的项目,有一个业务Check,需要用JavaScript实现:判断指定字符串是否为有效数字。这样的check以前已经碰到很多了,但每次都是解决了就完了,没有记录下来,等下次碰到时又要花很多的时间去写。东西是需要积累的,现在特记录下来,希望这样的工作不再重复太多,也与大家一起分享。

1 <!---

2 ================================================================================

3 机能概要  :check指定字符串是否为有效数字

4 作成者   :Peter Jin

5 作成日   :2010-04-23

6 ================================================================================

7 --->

8

9 <cfoutput>

10 <script type="text/javascript">

11 <!--

12

13 function BASEisNotNum(theNum)

14 {

15 //判断是否为数字

16 if (BASEtrim(theNum)=="")

17 return true;

18 for(var i=0;i<theNum.length;i++){

19 oneNum=theNum.substring(i,i+1);

20 if (oneNum<"0" || oneNum>"9")

21 return true;

22 }

23 return false;

24 }

25

26 function BASEisNotInt(theInt)

27 {

28 //判断是否为整数

29 theInt=BASEtrim(theInt);

30 if ((theInt.length>1 && theInt.substring(0,1)=="0") || BASEisNotNum(theInt)){

31 return true;

32 }

33 return false;

34 }

35

36 function BASEisNotFloat(theFloat)

37 {

38 //判断是否为浮点数

39 len=theFloat.length;

40 dotNum=0;

41 if (len==0)

42 return true;

43 for(var i=0;i<len;i++){

44 oneNum=theFloat.substring(i,i+1);

45 if (oneNum==".")

46 dotNum++;

47 if (((oneNum<"0" || oneNum>"9") && oneNum!=".") || dotNum>1)

48 return true;

49 }

50 if (len>1 && theFloat.substring(0,1)=="0"){

51 if (theFloat.substring(1,2)!=".")

52 return true;

53 }

54 return false;

55 }

56

57 function BASEtrim(str)

58 {

59 //去掉空格

60 lIdx=0;rIdx=str.length;

61 if (BASEtrim.arguments.length==2)

62 act=BASEtrim.arguments[1].toLowerCase();

63 else

64 act="all";

65 for(var i=0;i<str.length;i++){

66 thelStr=str.substring(lIdx,lIdx+1);

67 therStr=str.substring(rIdx,rIdx-1);

68 if ((act=="all" || act=="left") && thelStr==" "){

69 lIdx++;

70 }

71 if ((act=="all" || act=="right") && therStr==" "){

72 rIdx--;

73 }

74 }

75 str=str.slice(lIdx,rIdx);

76 return str;

77 }

78

79 // -->

80 </script>

81 </cfoutput>

代码经过测试,目前没有发现问题。如有朋友发现Bug,请提出,谢谢。