transfer numerical data end with 'M' and 'B'

Hi:
I have a numerical data that is for example, 1234567, I can translate to "%f" and "%e" format using Matlab, but I would like to transfer the data to something like this: 1.23M, where "M" represent "million", simliar if the data is even larger, over billion, I can transfer it as "1.2b".
is it possible to do this is Matlab?
Thanks!
Yu

4 commentaires

Dyuman Joshi
Dyuman Joshi le 7 Mar 2024
"is it possible to do this is Matlab?"
Yes, it is possible to do this in MATLAB.
That is simply data manipulation. Take the log() of the number to get the exponent and specify the corresponding alphabet/suffix accordingly.
Yu Li
Yu Li le 7 Mar 2024
yes I know there always a way, just want know if there is any official Matlab command can make this easily, instead of writting scirpt by myself.
Dyuman Joshi
Dyuman Joshi le 7 Mar 2024
Modifié(e) : Dyuman Joshi le 7 Mar 2024
No, there is no official MATLAB command that does that. You will have to write the code for it.
You can utilize the hint that I provided above.
P.S - Isn't the symbol for billion supposed to be B and not b?
Stephen23
Stephen23 le 7 Mar 2024
Modifié(e) : Stephen23 le 7 Mar 2024
As an alternative, you could download and try using my function NUM2WORDS():
It covers the entire DOUBLE range, has many options, and has been extensively tested:
num2words(1234567,'type','highest','sigfig',3)
ans = 'one point two three million'
Note that if you only use the first letter you will have a problem when you reach Quadrillion and Quintillion.
Or you could download my function NUM2SIP():
It provides all of the SI prefixes, and has also been extensively tested:
num2sip(1234567,3)
ans = '1.23 M'

Connectez-vous pour commenter.

Réponses (1)

You can define your own function. Here is an example:
sprintfkmb(12345678)
ans = "12.345678M"
sprintfkmb(-12345678)
ans = "-12.345678M"
sprintfkmb(-1238)
ans = "-1.238000k"
sprintfkmb(-1234567890123)
ans = "-1234.567890b"
function s = sprintfkmb(a)
str = ["", "k", "M", "b"];
e = floor(log10(abs(a)));
e3 = floor(e/3);
e3 = min(e3, 3);
s = sprintf("%.6f%s", a/(10^(e3*3)), str(e3+1) );
end

Catégories

En savoir plus sur Vector Fields dans Centre d'aide et File Exchange

Question posée :

le 7 Mar 2024

Modifié(e) :

le 7 Mar 2024

Community Treasure Hunt

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

Start Hunting!

Translated by