Search code examples
flutterdartnumber-formatting

dart numberformat how to set round or floor with some other case


codes bellow:

import 'package:intl/intl.dart';
void example1() {
  final numberFormat = NumberFormat.currency(locale: 'en_US', symbol: '');

  numberFormat.minimumFractionDigits = 2; // Minimum number of decimals
  numberFormat.maximumFractionDigits = 8; // Maximum number of decimals
  print(numberFormat.format(1));
  print(numberFormat.format(321.00000000000));
  print(numberFormat.format(321.12345678));
  print(numberFormat.format(321.12345678901));
}

out put:

1.00
321.00
321.12345678
321.12345679 // default round

Is there a function that can control it't round or floor?

Suppose there is a method: shouldFloor:

numberFormat.shouldFloor = true;
print(numberFormat.format(321.12345678901));
output: 321.12345678

What should be done?

Thanks!


Solution

  • you can create extension mehtod on it

    import 'dart:math';
    import 'package:intl/intl.dart';
    
    void main() {
      final numberFormat = NumberFormat.currency(locale: 'en_US', symbol: '');
    
      numberFormat.minimumFractionDigits = 2; // Minimum number of decimals
      numberFormat.maximumFractionDigits = 8; // Maximum number of decimals
      double number = 321.12345678901;
    
      print(numberFormat.formatWithCondition(number, shouldFloor: true)); // Output: 321.12345678
      print(numberFormat.formatWithCondition(number, shouldFloor: false)); // Output: 321.12345679
    }
    
    extension ConditionalFormatting on NumberFormat {
      String formatWithCondition(double number, {bool shouldFloor = false}) {
        if (shouldFloor) {
          double modifier = pow(10.0, this.maximumFractionDigits).toDouble();
          number = (number * modifier).floor() / modifier;
        }
        return this.format(number);
      }
    }