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

7 views (last 30 days)
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 ?

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)

Stephan on 5 Dec 2019
Walters answer is the correct one. What i provided here is a sleight-of-hand to achieve what i think you want to do.
Walter Roberson on 5 Dec 2019
x_new =
-3.14159265358929
Notice the last three digits displayed are 929 . Tis is the 9793 changed to 9287 and then rounded to one place shorter, 929 . MATLAB displays one fewer digits than the available precision:
>> fprintf('%.999g\n', x_new)
-3.1415926535892868542987343971617519855499267578125
NOtice this is 9_286_8 rather than 9_287 as that is the closest you can represent in binary floating point double for that magnitude of number. It is not able to achive 9_287 exactly but it is able to achieve something that rounds to that.
You might even prefer
>> fprintf('%.999g\n', x_new*(1+eps))
-3.14159265358928774247715409728698432445526123046875
which is 9_287_7 which rounds to 9_288 but at least has the 9_287 in it.
You should be giving up on the idea of replacing "last" digits in a binary floating point number.
Perhaps you should be considering using symbolic numbers, which are better at approximating decimal. (It is possible to prove that they are not truely decimal either though.)
Stephan on 5 Dec 2019
Thank you for the insight.

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.