我有具有不同值的字符串单元格数组:
v = {'12.4B', '145.3M', '34.3M', '1.2B'};
我想将它们转换为数字。使用sscanf函数我只能提取数值,但我想要的是根据字母将结果乘以十亿或百万。
您可以使用正则表达式替换 ( ) 分别将B
andM
替换为e9
and (科学记数法) ,然后将结果字符串转换为带有 的数字。e6
regexp
str2double
out = str2double(regexprep(v, {'B', 'M'}, {'e9', 'e6'}, 'ignorecase'))
您显然可以扩展它以包含任何其他必要的转换。
作为一个显示正在发生的事情的例子:
% Convert to scientific notation
B = regexprep(v, {'B', 'M'}, {'e9', 'e6'}, 'ignorecase')
% '12.4e9' '145.3e6' '34.3e6' '1.2e9'
% Convert to numbers
str2double(B)
% 12400000000 145300000 34300000 1200000000
% Data
v = {'12.4B', '145.3M', '34.3M', '1.2B'};
% Replace characters with numeric equivalents
v = strrep(v, 'k', 'e03'); % thousand
v = strrep(v, 'M', 'e06'); % Million
v = strrep(v, 'B', 'e09'); % Billion
v = strrep(v, 'T', 'e12'); % Trillion
...
% Convert to numeric values
w = str2double(v)