How to replace last 3 digits in a floating point number by another 3 digits

6 views (last 30 days)
Abdul Gaffar
Abdul Gaffar on 4 Dec 2019
Commented: Stephan on 5 Dec 2019
Let
x = -3.141592653589793;
a = 287;
then how can I replace last 3 digits of x i.e. 793 by a ?

Accepted Answer

Stephan
Stephan on 5 Dec 2019
Edited: Stephan on 5 Dec 2019
format long
x = -3.141592653589793;
a = 287;
x_new = sprintf('%.15f',x);
x_new(end-2:end) = (sprintf('%d',a));
x_new = str2double(x_new)
  3 Comments

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 5 Dec 2019
>> fprintf('%.999g\n', -3.141592653589793)
-3.141592653589793115997963468544185161590576171875
The last 3 digits of x are 875 not 393 .
MATLAB does not store numbers in decimal; it stores them in IEEE 754 Double Precision. It is not possible to exactly represent 1/10 in any finite number system based upon powers of 2, for exactly the same reason that you cannot exactly represent 1/7 in any file number system based upon powers of 10.

Community Treasure Hunt

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

Start Hunting!