フィルターのクリア

Why does "str2double" ignore misplaced commas in the input string?

15 ビュー (過去 30 日間)
MathWorks Support Team
MathWorks Support Team 2009 年 6 月 27 日
編集済み: MathWorks Support Team 2024 年 2 月 29 日
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:
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. How can I use "str2double" with this number formatting?

採用された回答

MathWorks Support Team
MathWorks Support Team 2024 年 2 月 27 日
編集済み: MathWorks Support Team 2024 年 2 月 29 日
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.
As a workaround, you can replace the commas with periods prior to calling str2double: 
str2double(strrep('4,01',',','.'));
Alternatively, if using character arrays, you can create your own MATLAB function that converts a string to a numeric value.
For example, if you would like to treat the comma as a decimal point and periods as the thousands separator, you can do the following, where "s" is the number to convert:
periods = (s == '.');
commas = (s == ',');
s(commas) = '.';
s(periods) = [];
str2double(s);
 
  1 件のコメント
Stephen23
Stephen23 2024 年 2 月 9 日
編集済み: Stephen23 2024 年 2 月 9 日
Note that this approach will not work with STRING arrays (properly introduced in R2017a), and refers to an outdated version of STR2DOUBLE.
A simple and robust approach that will work with STRING arrays, CHAR vectors (like this answer assumes) and also cell arrays of CHAR vectors is to simply use STRREP:
str2double(strrep('4,01',',','.')) % char vector
ans = 4.0100
str2double(strrep("4,01",',','.')) % string
ans = 4.0100

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by