Converting Numeric Types

Converting numeric types

It may be required at times to convert numbers from one type to another. Such as converting a floating point number to an integer or vice versa. So considering the example below:

Will produce:

6.833333333333333

As National 5 we have covered the Round function which could round this to the nearest number but if we wanted to convert this to an integer you would have to use the int() function. This converts the real (floating point) number to an integer. There is no rounding and the decimal portion of the number is truncated to just leave the integer portion of the number.

Such as shown below.

Will produce:

6

Use during file handling (converting strings to integers)

Consider if we were reading the csv file below of names and scores.

Jacynth Melhuish,7978

Desi Pagon,7250

Ethelind Glaserman,3634

Stephanus Garnson,5290

It is important that we read the score in as an integer and not a string so we can use the int function as shown in the code below.