skip to Main Content

I am trying to read data from a CSV file using Dart. The code I am using reads the lines from the file and splits them into columns using the split() method. One of the columns contains numeric data in string format, which I need to convert to a double. However, when I try to parse the string using the double.parse() method, I get a FormatException: Invalid double error. (the string is "1.5" which should work normally)

map[columns[5]] = (map[columns[5]] ?? 0) + double.parse(columns[3]);

this is the error displayed :

Reading from file: .\test.csv
Unhandled exception:
FormatException: Invalid double
"1.5"
#0      double.parse (dart:core-patch/double_patch.dart:112:28)
#1      main (...)
#2      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:295:33)
#3      _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:26)

I have tried using the trim() method to remove any whitespace characters from the string before parsing it, but the error persists. I have also checked the data in the CSV file and confirmed that it is correctly formatted as a decimal number.

2

Answers


  1. You will follow like this way

    void main() {
    var value1 = "1.5";
    var value2 = double.parse(value1);
    print(value1);
    print(value2);
    
    var value3 = value2 + double.parse(value1);
    print(value3);
    }
    

    Answer
    look into this image

    Login or Signup to reply.
  2. The error message:

    FormatException: Invalid double
    "1.5"
    

    indicates that you’re calling double.parse on the string "1.5" that includes the double-quote characters. You must strip them off first. There are a number of different ways that you could do that, for example:

    String unquote(String s) =>
        (s.length < 2 || !s.startsWith('"') || !s.endsWith('"'))
            ? s
            : s.substring(1, s.length - 1);
    
    void main() {
      var s = '"1.5"';
      print(s); // Prints: "1.5"
      print(unquote(s)); // Prints: 1.5
      print(double.parse(unquote(s))); // Prints: 1.5
    }
    

    Or even better would be to use a proper CSV parser, which should handle unquoting fields for you. Note that naively using String.split likely would result in incorrect results if your CSV file includes strings with embedded commas. (I have not personally used it, but package:csv probably would be suitable.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search