Home > Software engineering >  Dart double issue
Dart double issue

Time:11-02

dart cant change 14.99942 to 14.99; toStringAsFixed() doesn't work properly. Example:

(179.99 / 12.00).toStringAsFixed(2)

expected result: 14.99

actual result: 15.00

CodePudding user response:

A possible workaround is to define your own method.

String toFixedString(double nr){
  String n=nr.toString();
  final pos=n.indexOf('.');
  return n.substring(0,pos 3);
}

CodePudding user response:

Try with this Extension

extension NumberExtension on num {
  String toStringAsFixedWithoutRound(int n) {
    final r = toString().split(".");
    return "${r.first}.${r.last.substring(0, n)}";
  }
}
  • Related