Dart double truncate()
Syntax & Examples


double.truncate() method

The `truncate` method in Dart returns the integer obtained by discarding any fractional digits from the given number.


Syntax of double.truncate()

The syntax of double.truncate() method is:

 int truncate() 

This truncate() method of double returns the integer obtained by discarding any fractional digits from this.

Return Type

double.truncate() returns value of type int.



✐ Examples

1 Truncate a decimal number

In this example,

  1. We create a double variable num with the value 4.2.
  2. We use the truncate() method to truncate num by discarding any fractional digits and obtain an integer.
  3. We then print the truncated value to standard output.

Dart Program

void main() {
  double num = 4.2;
  int truncated = num.truncate();
  print('Truncated value of $num: $truncated');
}

Output

Truncated value of 4.2: 4

2 Truncate a decimal number (downwards)

In this example,

  1. We create a double variable num with the value 4.8.
  2. We use the truncate() method to truncate num by discarding any fractional digits and obtain an integer.
  3. We then print the truncated value to standard output.

Dart Program

void main() {
  double num = 4.8;
  int truncated = num.truncate();
  print('Truncated value of $num: $truncated');
}

Output

Truncated value of 4.8: 4

3 Truncate a negative decimal number

In this example,

  1. We create a double variable num with the value -4.5.
  2. We use the truncate() method to truncate num by discarding any fractional digits and obtain an integer.
  3. We then print the truncated value to standard output.

Dart Program

void main() {
  double num = -4.5;
  int truncated = num.truncate();
  print('Truncated value of $num: $truncated');
}

Output

Truncated value of -4.5: -4

Summary

In this Dart tutorial, we learned about truncate() method of double: the syntax and few working examples with output and detailed explanation for each example.