MATLAB Answers

How to change the field width of an exponential notation?

8 views (last 30 days)
Hi, Im trying to change the field width and the number of digits of the exponential, I will like to looks like enginnering notation:
and what I get its:
The formatSpec have the next form:
So, I dont know what Im doing wrong, its suppose to the total numbers before e its 21, 14 of them are located after the point. But doesnt seem to be like that.

  1 Comment

Stephen Cobeldick
Stephen Cobeldick on 4 May 2020
"...its suppose to the total numbers before e its 21"
The fieldwidth does not specify the number of digits, it specifies the total number of printed characters, including leading spaces, leading zeros, the significant digits, the decimal radix, the exponent character, the exponent digits, and any sign characters. All of these are included in the field width. If the number representation is shorter than the fieldwidth the output string will be padded with leading spaces or leading zeros.

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 4 May 2020
Edited: Stephen Cobeldick on 6 May 2020
Given >=2 digits, ensure >=3 digits:
>> val = 3.45866636216603e2;
>> str = sprintf('%.14e',val)
str =
>> str = regexprep(sprintf('%.14e',val),'(?<=\D)\d\d$','0$&')
str =
Given >=1 digits, ensure >=3 digits:
>> str = regexprep(sprintf('%.14e',val),{'(?<=\D)\d$','(?<=\D)\d\d$'},'0$&')
str =
A general solution that can provide any number of digits:
>> num = 3; % required number of digits
>> fun = @(s)sprintf('%0*u',num,sscanf(s,'%u'));
>> str = regexprep(sprintf('%.14e',val),'\d+$','${fun($&)}')
str =


Oscar Espinosa
Oscar Espinosa on 5 May 2020
But the function "regexprep" just add a zero before the exponential. In the case that the the exponent is 100 or more:
>> val = 3.45866636216603e+100;
>> regexprep(sprintf('%.14e',val),'\d+$','0$0');
ans =
There is another way to get the exponential? Or I have to use a cycle "if" for the recognition of the exponent.

Sign in to comment.

More Answers (0)


Community Treasure Hunt

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

Start Hunting!