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
You will follow like this way
Answer
The error message:
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: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, butpackage:csv
probably would be suitable.)