2

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.

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

4 Comments

I was thinking how to do this with a map-like thing, and then your answer came in
@RodyOldenhuis Yea that's one of the things I like about regexprep!
yeah I kinda hover between regexprep (flexible, powerful, awesome, ...) and strrep (more readable, much faster, more portable, ...). Oh well, this sure beats my answer in this case :)
Thank you for the solution, @Suever
2
% 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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.