Pranasas
Pranasas

Reputation: 596

How to add leading zeros in MatLab (number formatting)?

Here is a very specific example

>> S = num2str(12345,'%6.0e')
S =
1e+04

and that's just great since I want only my first digit and an exponential notation. However I also want to add leading zeros to the exponent in order to fill the width, but I cannot quite find the way to get the following...

1e+004

Meanwhile it's very straighforward to pad the significant digits with leading zeros

>> S = num2str(12345,'%06.0e')
S =
01e+04

So is there an appropriate formatting for what I want? Or a trick to accomplish it quickly?

Upvotes: 0

Views: 4080

Answers (2)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

The exponent is always a zero-padded two-digit value. To add, say, two zeros you can use

regexprep(num2str(12345, '%6.0e'), '\+', '\+00')

and achieve

ans =
1e+0004

Edit: To cover negative exponents you may use

regexprep(num2str(0.12345, '%6.0e'), '(\+|\-)', '$100')

to achieve

ans =
1e-0001

And, to cover three-digit exponents

regexprep(num2str(1e-100, '%6.0e'), '(\+|\-)(\d{2,3})$', {'$10$2', '$10$2'})

ans =
1e-0100

regexprep(num2str(1e-10, '%6.0e'), '(\+|\-)(\d{2,3})$', {'$10$2', '$10$2'})

ans =
1e-0010

Upvotes: 2

DrunkenDuck
DrunkenDuck

Reputation: 130

Well, I think you have to edit, what you say you want is wat you get :D

however, if I understood correctly what you are looking for, this function will help you

function printX(x, digits)
    format = sprintf('\t%%.%de', digits - 1);
    strcat(inputname(1), ' = ', sprintf(format, x))
end

Upvotes: 0

Related Questions