Truncate to 2 decimal places without rounding

Viewed 3659

Can't find or work out a solution to this that works with Dart.

I've already tried:
1. toStringAsFixed() - this rounds
2. double.parse(number.toStringAsFixed()) - this rounds
3. num - num % 0.01 - this rounds

I've found some solutions on SO but they either use functions that aren't available on Flutter/Dart or didn't work for me.

Any help would be greatly appreciated.

4 Answers

To build on @Irn beautiful Answer.

The function below lets you specify how many fractional digits / how many decimal places you want

double truncateToDecimalPlaces(num value, int fractionalDigits) => (value * pow(10, 
   fractionalDigits)).truncate() / pow(10, fractionalDigits);

Example

truncateToDecimalPlace(4321.92385678, 3) // 4321.923

Or my favorite way is to use Dart extensions

extension TruncateDoubles on double {
   double truncateToDecimalPlaces(int fractionalDigits) => (this * pow(10, 
     fractionalDigits)).truncate() / pow(10, fractionalDigits);
}

This lets you call the function on a double object like thus

Usage

4321.92385678.truncateToDecimalPlaces(3); // 4321.923

Try

double truncateToHundreths(num value) => (value * 100).truncate() / 100;

There will be cases where you lose precision, but that requires you to use almost all 53 bits of double precision in the number (when multiplying by 100 loses precision to begin with).

Going trough strings is a significant overhead that I would avoid if possible, unless you actually expect to convert the number to a string anyway afterwards.

(value * 100).truncateToDouble() / 100

Example:
var lat = 29.4562

lat * 100 = 2945.62
2945.62 truncateToDouble() = 2945
2945 / 100 = 29.45

I have used the below method

String toFixed(double value, [int decimalPlace = 1]) {
  try {
    String originalNumber = value.toString();
    List<String> formattedNumber = originalNumber.split('.');
    return "${formattedNumber[0]}.${formattedNumber[1].substring(0, decimalPlace)}";
  } catch (_) {}
  return value.toString();
}
Related