How to round the decimals to required digits.

10 views (last 30 days)
If the values of a in double is
a=55.619999999999999;
I want to use "round" function i.e result = round(a,4); now my expected result should be result = 55.6199.
But round function is not working in MATLAB Got the below error
>> a=55.619999999999999
a =
55.619999999999997
>> round(a,4) Error using round Too many input arguments.
Any talented guys please help out.
Thank you in advance.
  3 Comments
Thouheed Shaik
Thouheed Shaik on 9 Jun 2017
Edited: Walter Roberson on 9 Jun 2017
Hi KSVV,
I want limit it to 4 decimals and use it for setting flags exactly at 55.6199
There is a command shown in matlab as below please go through the link provided
Try this Example
Round the elements of a vector to retain 2 significant digits.
format shortg
x = [1253 1.345 120.44]
x =
1253 1.345 120.44
y = round(x,2,'significant')
y =
1300 1.3 120
Walter Roberson
Walter Roberson on 9 Jun 2017
You are looking at the documentation for a release newer than what you have.
"and use it for setting flags exactly at 55.6199"
You will need to switch to the symbolic toolbox for that. MATLAB does not represent numbers in decimal. 55.6199 does not exist exactly in IEEE 754 binary double precision numbers.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 9 Jun 2017
The ability to supply a number of decimal places for round() was introduced in R2014b.
"now my expected result should be result = 55.6199"
You cannot get that except for presentation purposes. The internal representation of 55.619999999999999 is not 55 + 619999999999999 / 10^15 : the internal representation is equivalent to 55.61999999999999744204615126363933086395263671875 . The internal representation of 55.6199 is equivalent to 55.619900000000001227817847393453121185302734375
If you need 55.6199 exactly to be stored, you will need to switch to the symbolic toolbox.
  1 Comment
Thouheed Shaik
Thouheed Shaik on 9 Jun 2017
Thank you for the information.
May be you are right, I was using R2013b, i will check in R2014b if round(x,n) is working or not.

Sign in to comment.

More Answers (1)

John
John on 9 Jun 2017
Hi,
I think the rounded value (4 digits) for a would be a = 55.6200 (due to the trailing nines. If you want to dump the rest of the nines (truncate) to get a = 55.6299 you could use:
fix(a*1000)/1000
where a number of zeroes are the decimal points you want. Taken from https://se.mathworks.com/matlabcentral/answers/234470-truncating-a-number-without-rounding
I hope it helps...

Tags

Community Treasure Hunt

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

Start Hunting!