user1635694
user1635694

Reputation: 1

How do I avoid errors when converting strings to numbers if I don't know whether I have floats or integers?

I have stringgrid on delphi form and i am trying to divide values of one cell with value of another cell in another column.

But the problem is, stringgrid cells are populated with different types of numbers, so I am getting ConvertErrors. For example the numbers in cells can look like 0.37 or 34 or 0.0013 or 0.00 or 0.35 or 30.65 or 45.9108 or 0.0307 or 6854.93.

In another words I never know is it going to be real, float, integer or any other kind of type in those cells.

I have looked everywhere on internet but no luck. Anyone any ideas. By the way I am not exactly Delphi expert. Thanks.

Upvotes: 0

Views: 387

Answers (3)

ssh
ssh

Reputation: 985

SysUtils has many functions such as TryStrToFloat, TryStrToInt, TryStrToInt64 etc for this purpose. These functions accept a reference parameter (var parameter) for returning the converted value and function itself returns true if the conversion is successful.

If you are sure that the string has a valid number then you can check the input string to see if it has a decimal point before deciding which function to use.

Upvotes: 3

mathematician1975
mathematician1975

Reputation: 21351

For each string, convert it first to a float value using StrToFloat function in SysUtils.pas . This should allow for any numerical type to be dealt with (unless you have something unusual like complex numbers). As you have some zero values in your list above you should also ensure that you check for divide by zero conditions as this will also potentially throw an exception.

Upvotes: 3

iMan Biglari
iMan Biglari

Reputation: 4776

Treat all the numbers as float. Use StrToFloat, divide the numbers, and then convert the result back to string with FloatToStr. If the result is an integer, no decimal point would be produced.

Upvotes: 2

Related Questions