ibezito
ibezito

Reputation: 5822

MATLAB's num2str is inconsistent

I want to receive the string representation of a number, 2 points after the dot.

I'm using MATLAB R2015a, and noticed that num2str function returns inconsistent results:

for 0.511 I get the required result (0.51):

num2str(0.511,2)

ans =

0.51

for 1.711 I get 1.7 instead of 1.71:

num2str(1.511,2)

ans =

1.5

Anyone knows why?

Upvotes: 0

Views: 812

Answers (2)

user2999345
user2999345

Reputation: 4195

the 'precision' scalar input to num2str is the number of significant digits. if you want to have 2 figures after the decimal point use the 'formatSpec' string argument:

num2str(0.511,'%.2f')
    0.51
num2str(1.511,'%.2f')
    1.51

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520908

From the documentation for num2str():

s = num2str(A,precision) returns a character array that represents the numbers with the maximum number of significant digits specified by precision.

In other words, the second parameter controls the total number of significant figures, not the number of decimal places.

If you want to round to two decimal places, then use the round() function. You can try rounding the number before calling num2str():

num2str(round(1.511,2))

Upvotes: 2

Related Questions