How To Convert Float Into Integer In Flutter?

In flutter, there are few functions that convert a float or double data type into an integer. In this article, we will learn float value conversion to an integer with the following functions,

  • toInt() method
  • floor() method
  • round() method
  • ceil() method

Before going into detail, let’s initialize a variable with the var keyword.

var tablePrice = 50.5;

It has double data type, if you want to check it further then you can use runtimeType property to find out the current data type of a variable.

print(tablePrice);
// Output : 50.5

print(tablePrice.runtimeType);
// Output : double

Next, to convert the table price into an integer we will be using different methods.

The toInt() Method

The toInt() method converts the double value into an integer.

var convertToInteger = tablePrice.toInt();

print(convertToInteger);
// Output : 50
print(convertToInteger.runtimeType);
// Output : int

If you notice, the toInt() method converted the data type without rounding up the value, that’s why it returns 50.

The floor() Method

The floor() method converts the double value into an integer without rounding up. For table price, it will return a similar result that the toInt() method returned.

var convertToInteger = tablePrice.floor();

print(convertToInteger);
// Output : 50

print(convertToInteger.runtimeType);
// Output : int

The round() Method

The round() method converts the double value into an integer and also it rounds up the value. This means for the table price, the round() method will convert the value into an integer and return 51 instead of 50.5 or 50.

var convertToInteger = tablePrice.round();

print(convertToInteger);
// Output : 51

print(convertToInteger.runtimeType);
// Output : int

The ceil() Method

The ceil() method converts the double value into an integer. It rounds up the result.

var convertToInteger = tablePrice.ceil();

print(convertToInteger);
// Output : 51

print(convertToInteger.runtimeType);
// Output : int


Related Posts