MATLAB Answers


how to round the decimal point?

Asked by bsd
on 27 Sep 2011


I need to round the decimal number to 2 decimal places. What is the function in matlab, to the above rounding off. Looking for your reply.



Log in to comment.


3 Answers

Answer by Jan Simon
on 27 Sep 2011

x = rand * 1000;
y = floor(x * 100) / 100;

See: floor, ceil, round, fix.

A general method to find help is searching in the documentation:

docsearch round


Show 1 older comment

In you original question you ask for "rounding off". If you want to round to the nearest: round(0.1698 * 100) / 100 replies 0.17

>> sprintf('%.99g\n',round(0.1698 * 100) / 100)
ans =

>> num2hex(round(0.1698 * 100) / 100 )
ans =
>> num2hex(round(0.1698 * 100) / 100 - 8*eps(.01))
ans =

If you compare the hex of the two floating point values, you will note that this second value is the first representable value smaller than the original value

>> sprintf('%.99g\n',round(0.1698 * 100) / 100 - 8*eps(0.01))
ans =

and you can see from the extended printout that it is below 0.17 whereas the other value was above 0.17. We have thus experimentally demonstrated that there is no exact representation in binary floating point arithmetic for 0.17 exactly.

@BSD: Does Walter's correct argument concern your work? Or is 0.1700000000000000xyz... accurate enough for your demands?

Log in to comment.

Answer by Walter Roberson
on 27 Sep 2011

This is not possible in binary floating point arithmetic, unless the rounded fraction happens to end up being 0.0, 0.25, 0.5, or 0.75

Binary floating point arithmetic cannot exactly represent the fraction 1/100 in any finite amount of storage, for the same reason that decimal arithmetic cannot exactly represent the fraction 1/7 in any finite amount of storage.


Log in to comment.

Answer by Jigar Gada on 28 Aug 2012

Thanks a lot.. It was so simple.


Log in to comment.

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today