In Dart, the `
truncate()` methods are used to truncate a floating-point number to an integer value. Dart provides two methods for truncation:
1. `truncate()` : The `
truncate()` method returns the integer obtained by discarding any fractional digits from a floating-point number towards zero.
double number = 3.8;
int truncatedNumber = number.truncate();
print(truncatedNumber); // Output: 3
In this example, the `
truncate()` method is called on the `
number` variable, which has a
value of 3.8. The method truncates the decimal part, resulting in an integer value of 3.
2. `truncateToDouble()` : The `
truncateToDouble()` method works similarly to `
truncate()`, but it returns the result as a `
double` instead of an `
int`.
double number = 5.6;
double truncatedNumber = number.truncateToDouble();
print(truncatedNumber); // Output: 5.0
Here, the `
truncateToDouble()` method is used on the `
number` variable with a value of 5.6. It truncates the decimal part and returns the result as a `
double`, resulting in the value 5.0.
The `truncate()` methods are useful when you want to discard the fractional part of a floating-point number and obtain the integer value. It can be used in various scenarios, such as converting a floating-point number to an integer index or performing calculations where only the whole number portion is relevant.