VBS convert string to floating point

后端 未结 3 1902
广开言路
广开言路 2021-01-21 10:36
Dim strnumber
strnumber = \"0.3\"

Dim add
add = 0.1

Dim result 
result  = strnumber +  add

MsgBox result

I want to get 0.4 as result, b

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-21 11:12

    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
    

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

    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.

提交回复
热议问题