I have cell array of strings with different values:
v = {'12.4B', '145.3M', '34.3M', '1.2B'};
I would like to convert them to numbers. Using sscanf function I can extract only numeric values, but what I want is to multiply the result by billion or million according to the letter.
You can replace B
and M
with e9
and e6
respectively (scientific notation) using regular expression replacement (regexp
) and then convert the resulting strings to a number with str2double
.
out = str2double(regexprep(v, {'B', 'M'}, {'e9', 'e6'}, 'ignorecase'))
You can obviously expand this to include any other necessary conversions.
And as an example showing what's happening:
% 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