VBS convert string to floating point

后端 未结 3 1901
广开言路
广开言路 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:03

    Has to do with your locale settings. Automatic conversion (as well as explicit one) observes it in the same manner as in CStr() function.

    E.g. in my locale CStr( 0.3) results to 0,3 that is invert to CDbl("0,3") while CDbl("0.3") results to an error.

    BTW: always use option explicit and, for debugging purposes, On Error Goto 0

    0 讨论(0)
  • 2021-01-21 11:07

    Following below procedures can help:

    1. Replacing the dot(".") with comma (",") in the string
    2. change the string to double by Cdbl

    example:

    dim a,b,c
    
    a="10.12"
    
    b="5.05"
    
    a=Replace(a,".",",")
    
    b= Replace(b,".",",")
    
    c=Cdbl(a)+Cdbl(b)
    
    msgbox c
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题