Academia
Academia

Reputation: 4124

num2str with a specific format in MATLAB

>> x = 14.021
>> num2str(x,'%4.5f')

I want to get this as a result:

0014.02100

But, MATLAB just answers me with:

14.02100

Upvotes: 2

Views: 14167

Answers (1)

Chris
Chris

Reputation: 46366

You should use sprintf. For example:

x = 14.021
sprintf('%010.5f', x)

Note that you don't need to use num2str.

The first argument to sprintf is the format specifier which describes how the resulting text should be displayed. The specifier begins with %, the leading 0 tells sprintf to pad the string with zeros. Loosely, the .5 tells it to print five digits to the right of decimal point and the f tells it we want to format it like a floating point number.

Upvotes: 5

Related Questions