Formating String Parameter Left of Decimal
1 view (last 30 days)
Show older comments
In the following code, I want to create the str variable to read: Radius=100E-6 meter
However, I keep getting: Radius=1.00E-4 meter
I can't seem to force it to place more digits to the left of the decimal. How do I revise sprintf to produce the former instead of the latter?
a=100E-6;
str=sprintf('Radius=%3.0E meter,',a);
I know the answer is probably something simple, but I just can't seem to figure it out.
Thanks in advance,
M Ridzon
2 Comments
Stephen23
on 25 Sep 2017
The standard C-based MATLAB command sprintf does not produce "engineering" exponents, it always produces exponents with one digit before the decimal point. You might like to read these (but don't use the first answer!):
Stephen23
on 25 Sep 2017
Edited: Stephen23
on 25 Sep 2017
>> num2sip(1.234e-4)
ans = 123.4 u
Following your example you could do something like this:
>> sprintf('Radius = %smeter',num2sip(1.234e-4,[],true))
ans = Radius = 123.4 micrometer
Note that unlike the accepted answer num2sip correctly returns the requested precision, regardless of the order of the number:
>> num2sip(1.4567e-4)
ans = 145.67 u
>> num2sip(1.4567e-5)
ans = 14.567 u
>> num2sip(1.4567e-6)
ans = 1.4567 u
Accepted Answer
Star Strider
on 25 Sep 2017
I wrote a little utility function for my own purposes to do this a while ago:
engstr = @(x) [x*10.^(-3*floor(log10(abs(x))/3)) 3*floor(log10(abs(x))/3)]; % Engineering Notation Mantissa & Exponent
x = 1E-4;
Result = sprintf('%3.0fE%-.0f', engstr(x))
Result =
'100E-6'
Configure the sprintf format string to produce the output you want.
3 Comments
More Answers (1)
John D'Errico
on 25 Sep 2017
Personally, 100e-6 seems like a silly and confusing way to write the number 1e-4. And at some point in my educational career, I even spent some time as an engineer. What you are probably looking for is known as engineering notation.
format SHORTENG
a = 1e-4
a =
100.0000e-006
So can you just display the number directly? I don't see a simple way to force sprintf to work, as it does not seem to include the engineering notation form as an option.
2 Comments
John D'Errico
on 25 Sep 2017
Personally, I was surprised that sprintf did not offer engineering notation as an option. I suppose you could write a utility that worked like sprintf, but used engineering notation. It would take some amount of effort, that might not be worth the mental energy expended.
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!