reduce precision of a number

1,018 views (last 30 days)
Dwight on 22 Jun 2013
Commented: Walter Roberson on 19 Aug 2019
I am having a problem trying to reduce precision output of a number
for example
x = 1.123456 I want x = 1.123 (only 3 values after a decimal and not a string)
I use x = round(x*1000)/1000 and get x = 1.1230 (I dont want the end zero)
I use x = sprintf('%.3f',x) and get a string '1.123' (i dont want a string)
so i use x = str2num(sprintf('%.3f',x)) and get x = 1.1230 (again with the zero)
please help me remove a zero at the end. I am not concerned with precision.
Walter Roberson
Walter Roberson on 23 Feb 2017
fprintf() sends to the command window output or a file, instead of constructing a string to be returned. The return value from fprintf() is the number of characters printed, not the string. fprintf() and sprintf() have exactly the same format codes.

Sign in to comment.

Answers (4)

Azzi Abdelmalek
Azzi Abdelmalek on 22 Jun 2013
Edited: Azzi Abdelmalek on 22 Jun 2013
When you use x for calculation use
out = str2num(sprintf('%.3f',x)) % when x is not displayed, the 0 does not appear!
x = round(x*1000)/1000
When you want to display it use
Iain on 25 Jun 2013
find( abs(x(:,1)-b) < 1/1000 )
would be better.

Sign in to comment.

Walter Roberson
Walter Roberson on 22 Jun 2013
At the command prompt give the command
format short g
Note: it is not possible to represent 1.123 exactly as a binary double precision number. The closest representable number is 1.1229999999999999982236431605997495353221893310546875
Walter Roberson
Walter Roberson on 19 Aug 2019
vpa() requires the Symbolic Toolbox

Sign in to comment.

Steven Lord
Steven Lord on 23 Feb 2017
This is an old discussion, but if you're using release R2014b or later you can round to a specified number of digits.
Walter Roberson
Walter Roberson on 21 Sep 2017
MATLAB uses IEEE 754 Binary Double Precision to represent floating point numbers. All floating point scheme that uses binary mantissas cannot exactly represent 1/10, just like decimal representation schemes cannot exactly represent 1/3 or 1/7 .
IEEE 754 also defined a Decimal Double Precision representation scheme, which can represent 2.123 exactly. However, computing those values in software is much slower. The only systems I know of that implement IEEE 754 Decimal Double Precision in hardware are the IBM z90 series.
If you need a certain specific number of decimal places to be stored, then use rationals with a power-of-10 denominator.

Sign in to comment.

Francis Agbali
Francis Agbali on 24 Mar 2019
I would try using
format short

Community Treasure Hunt

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

Start Hunting!