Convert Variable From Float To Int In Dart
Code snippet for how to Convert Variable From Float To Int In Dart with sample and detail explanation
Understanding the process to convert a variable from float to int in Dart is absolutely essential for every Dart programmer because it constitutes the basics of typecasting. This article will introduce a comprehensive guide on how to execute this process using an illustrative code snippet followed by an in-depth explanation.
Code snippet for Float to Int conversion
void main() {
double myFloatNum = 45.65;
int myIntNum = myFloatNum.toInt();
print('The converted integer value is ${myIntNum}');
}
Code Explanation for Float to Int Conversion
Firstly, we will focus on understanding the fundamental attributes of our code for float to int conversion, step by step.
Step 1: Defining the Main Function
We start by defining the main function void main() { ... }
. It’s the entry point for our Dart program. All Dart programs begin with this function.
void main() {
// Code goes here
}
Step 2: Declare and Initialize our Float Variable
Next, we declare a double variable myFloatNum
and initialize it with a floating-point number 45.65
. This is the number that we are going to convert to an integer.
double myFloatNum = 45.65;
Step 3: Convert the Float to an Integer
Moving forward, we use the toInt()
method to convert the floating-point number to an integer. We declare a new integer variable myIntNum
and store the converted integer in it. Take note that toInt()
is a built-in Dart method used to convert float (double in Dart) type data to integer. After conversion, the number is rounded down.
int myIntNum = myFloatNum.toInt();
Step 4: Display the Converted Result
For the final step, we use the print()
function to display the converted result. It is important to know that variables can be embedded directly into Dart strings (using ${}
). In this example, ${myIntNum}
will output the value held by the variable.
print('The converted integer value is ${myIntNum}');
To conclude, the initially floating-point number was 45.65
, and after conversion, the output should be 45
, where the decimal portion is dropped. This process is a clear illustration of how to handle and convert types in Dart. Happy coding!