1,285 views (last 30 days)

Show older comments

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
on 23 Feb 2017

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!

%or

x = round(x*1000)/1000

When you want to display it use

sprintf('%.3f',x)

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

Steven Lord
on 23 Feb 2017

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.

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

Start Hunting!