F

LutterAdda

Double to int in flutter

Introduction

In Flutter, there are times when we need to convert a double value to an integer. For this purpose, we can use the built-in dart method toInt(). This will return an integer value for the given double value.



    double myDouble = 3.14;
    int myInt = myDouble.toInt();
    print(myInt); // Output: 3
                    


When we are converting a double to an integer, we must always keep in mind that the digits after the decimal points will be truncated. So if you're looking to round the double value instead, you can use the round() method.



    double myDouble = 3.76;
    int myRoundedInt = myDouble.round();
    print(myRoundedInt); // Output: 4
                    


Using floor()

The floor() method returns the largest integer less than or equal to the given number. In other words, it rounds the number down to the nearest integer. We can say that it truncates the decimal points and keeps the integer part intact.



    Example:

    3.9.floor() will return 3.
    -3.9.floor() will return -4.
                    


Using ceil()

The ceil() method returns the smallest integer greater than or equal to the given number. In other words, it rounds the number up to the nearest integer. It rounds off the number and returns an integer.



    Example:

    3.1.ceil() will return 4.
    -3.1.ceil() will return -3.
                    


Summary

floor() rounds towards negative infinity.


ceil() rounds towards positive infinity.


These methods are useful when you need to ensure that a number is rounded to the nearest whole number, either down (floor()) or up (ceil()).