MATLAB: Does STR2DOUBLE ignore misplaced commas in the input string

europeeuropeanMATLABstr2num

When I use the STR2DOUBLE function to convert textual data to numerical data, misplaced commas are ignored. The result is that invalid numbers are interpreted; for example, the following call returns 401 instead of NaN:
str2double('4,01')
The documentation states that STR2DOUBLE can handle strings with commas separating the thousands places, but ignoring commas can lead to major errors in some geographic locations where ',' is used instead of a decimal point. The string '4,01' is a valid way to represent 4.01, but STR2DOUBLE returns an invalid numerical value.

Best Answer

The STR2DOUBLE function eliminates all commas from the input string before attempting to determine its numeric value. The STR2DOUBLE function does not have the ability to recognize misplaced commas or commas that are used as decimal separators.
To work around this issue, you must create your own MATLAB function that converts a string to a numeric value. The code in str2double.m can be used as a starting point. (Be sure you do not modify or overwrite the original version of str2double.m).
For example, if you would like to treat the comma as a decimal point and periods as the thousands separator, you can copy the code from str2double.m, rename the function, and change line 37 from:
s(s==',') = [];
to the following:
periods = (s == '.');
commas = (s == ',');
s(commas) = '.';
s(periods) = [];
Change the function calls in line 201 and 210 from:
x(k) = str2double(s{k});
to the following:
x(k) = newfunctionname(s{k});