Search code examples
delphidelphi-7

Delphi 7 Sum of two numbers with decimals


Beginner here :)

I am trying to make a Delphi application that requires user input and then adds and subtracts those variables.

I succeeded in creating the application and everything works fine except:

Cannot find the proper way to deal with numbers with decimals.

Example:

A,B,C,D,E,F: string; A1,B1,C1,D1,E1,F1: integer:

I use InputBox to get the user inputs. I store the inputs in string variables. I convert the string variable to integer with A1 := strToint(A); At the end, I want to: A1+B1-C1-D1-E1-F1 End everything works if the input is integer. The problem arises if the user enter a number with decimals.

I have searched all over the place but could not find an answer to my problem.(Or I did not understood)

Anyone can please point me in the right direction?

Thank you.


Solution

  • You are trying to convert a string to a floating point value.

    First of all you need to change your Integer variables to be of type Double. This will allow you to store values that are not integers.

    Secondly you need a different function to perform the conversion. You should use TryStrToFloat. This attempts to convert from string to floating point. If the conversion succeeds the function returns True, otherwise it returns False. For example:

    var
      str: string;
      value: Double;
    ....
    if not TryStrToFloat(str, value) then
    begin
      // handle error in some appropriate way
    end;
    // do something with value