skip to Main Content

How do you convert the double 15.350000000000001 automatically to a string "13.35" without having to specify the number of decimal places?
I know that there is double.toStringAsFixed but it has the huge drawback that it converts 1 to "1.00" which is not what I want.
I’m looking for a function which can pretty-print every double with automatic decimal places detection.

2

Answers


  1. You could convert it to String and then do some logic / iteration through the decimals to determine the index when you should accept it and then use toStringAsFixed or you could use a Regexp to find and acceptable match:

    final reg = RegExp(r'^d+(.(d*?)(?=0{2}|$))?');
    print(reg.stringMatch(15.350000000000001.toString())); /// convert it to double? at the end with num/double.parse() (it's almost guarantee to be not null because you convert a number to String back and forth) with .to
    

    The pattern:

    ^                      starts with
    d+                    one or more digits (whole numbers)
    .                     decimal point
    (d*?)                 zero or more digits (lazy, if there are not digits end)
    (?=0{2}|$)             asserts that at this point there is double zero or end of line ($ is the end in regex)
    (.(d*?)(?=0{2}|$))?  wrapping it in () with a ? at the end means that check this whole group happens once or none (for example a whole number means there is not . nor decimals, so it will not fail)
    

    I use 00 as the end because sometimes you could find acceptable things like 4.090000001 so it can retrieve 4.09, but you can investigate more of what is your need and change to accept the first zero after a . if there is a number after that, is up to you

    Login or Signup to reply.
  2. My solution (FormatFloat from Delphi) using intl package:

    import "package:intl/intl.dart";
    
    String formatFloat(String fmtStr, double value) {
      return NumberFormat(fmtStr).format(value);
    }
    

    Using:

    formatFloat('0.00##', value);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search