VBS将字符串转换为浮点数 [英] VBS convert string to floating point



Dim strnumber
strnumber = "0.3"

Dim add
add = 0.1

Dim result 
result  = strnumber +  add

MsgBox result

我想得到 0.4 作为结果,但得到 3.1.我尝试了 clng(strnumber)int(strnumber),但没有任何效果.肯定有一个简单的解决方案,但我找不到.

I want to get 0.4 as result, but get 3.1. I tried clng(strnumber) and int(strnumber), nothing works. There is a simple solution for sure but I won't find it.


result  = CDbl(Replace(strnumber,".",",") +  add



You want to add two numbers. So you should use numbers (and not a string (strnumber) and a number (add):

>> n1 = 0.3
>> n2 = 0.1
>> r  = n1 + n2
>> WScript.Echo r

正如您从输出 (0,4) 中看到的,我使用的语言环境(德语)使用,"作为十进制点".但是文字总是使用.".因此,通过使用正确的数据类型,只要您不需要处理外部字符串数据(来自文件或用户输入),您就可以以独立于语言/区域设置的方式编写脚本.然后您必须修改输入,然后将其提供给像 CDbl() 这样的转换函数.对于可以使用 Replace(inp, badmarker, goodmarker) 完成的简单情况.

As you can see from the output (0,4), I'm using a locale (German) that uses "," as decimal 'point'. But literals always use ".". So by using the proper data types you can write your scripts in a language/locale independent fashion as long as you don't need to process external string data (from a file or user input). Then you have to modify the input before you feed it to a conversion function like CDbl(). For simple cases that can be done with Replace(inp, badmarker, goodmarker).

附言你说你试过 clng(strnumber) 和 int(strnumber)".您应该尝试过 CDbl().CLng() 尝试获取一个长整数(参见 CInt()),Int() 从数字中删除/舍入分数.

P.S. You said you " tried clng(strnumber) and int(strnumber)". You should have tried CDbl(). CLng() tries to get a long integer (cf. CInt()), Int() removes/rounds the fraction from number.


登录 关闭
发送“验证码”获取 | 15天全站免登陆