truncate function Null safety

double truncate(
  1. double val,
  2. int fractionDigits
)

Truncate the decimal part of a double number. This function is very useful for compere two double numbers.

  • val : a double value
  • fractionDigits : number of decimal digits

References

  1. "How do you round a double in Dart to a given degree of precision AFTER the decimal point?". https://stackoverflow.com/a/53500405/6846888. Retrieved 2019-07-15.

Examples

print(truncate(1.4747474747474747, 3));

/* output:
1.475;
*/

Implementation

double truncate(double val, int fractionDigits) {
  var mod = pow(10.0, fractionDigits).toDouble();
  return ((val * mod).round().toDouble() / mod);
}