SvenLie
SvenLie

Reputation: 23

dividing 2 doubles results always in 1 vb

both txtfield1 and txtMCLCCurrToEUR are doubles

(originally strings converted to double, both are the values of forex with 5 digits after decimal point)

Dim f1 As Double
txtField2.Text = (Double.TryParse(txtMCLCurrToEUR.Text, f1) / Double.TryParse(txtField1.Text, f1)).ToString("N5")

irrespective of their values, I always end up with 1 in the txtField2.text

I seem to have overlooked something essential, but for the life of me -- I don't see what it could be...

any help would be much appreciated!

Upvotes: 0

Views: 74

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29026

Double.TryParse() will return a Boolean value(true/false), true for success and false in case of failure of conversion from string to double. so that if you apply division over Boolean values it will gives you result as either 1 or 0.

You can realize this by running your program by enabling Option Strict On

consider one example:

 Dim a = True
 Dim b = True
 Dim c = CDbl(a) / CDbl(b) ' will gives you output as 1 

Where as

 Dim a = True
 Dim b = False
 Dim c = CDbl(a) / CDbl(b) ' will gives you output as -1.#INF

Simply you can do this without using any third variable, like the following.

txtField2.Text = (Val(txtMCLCurrToEUR.Text) / Val(txtField1.Text)).ToString("N5")

Val() will return 0 in case it failed to convert the input string/null

Upvotes: 1

2red13
2red13

Reputation: 11227

You should not use f1 for both conversions, the second one would overwrite the first and the result is always one. Tryparse has no return value, only a flac vor succeed or not.

Dim f1 As Double
 Double.TryParse(txtMCLCurrToEUR.Text, f1)
Dim f2 As Double
 Double.TryParse(txtField1.Text, f2)
txtField2.Text =  (f1/f2 ).ToString("N5")

Upvotes: 1

Related Questions