- a number written in base 2
- some kind of encoded number (e.g. binary floating point)
How to remove the unwanted zero at the end in the floating point variable?
24 views (last 30 days)
Show older comments
Hello,
I have a floating point variable that I need to convert into into the binary.
So, at first i want to limit the number the digit after the decimal. To do that I am using output=round(input,4).
But after this, i get some unwanted zero that I do not want.
For example:
a=1.006600000000000 but I want only 1.0066
b=round(a,4) % the output is still 1.006600000000000
And then I want to convert it to binary (only 1.0066 to binary). How can I do that?
Please help
Thank you..
0 Comments
Answers (2)
Stephen23
on 9 Mar 2021
Edited: Stephen23
on 9 Mar 2021
"How to remove the unwanted zero at the end in the floating point variable?"
Trailing zeros are just an artifact of displaying a specific binary value as a decimal number at a specific precision.
" a=1.006600000000000 but I want only 1.0066"
Binary floating point numbers do not store any information about how many decimal digits you want. Their precision is fixed to some number of binary digits, which cannot be changed. Both of your numbers are exactly the same:
a = 1.006600000000000;
b = 1.0066;
isequal(a,b)
When you round to some (decimal) magnitude, you might get the same number or a slightly different number, it really does not make much difference in this case because both of them will display as the same value anyway:
b = round(a,4)
isequal(a,b)
b+100*eps() % a slightly different number displays the same
If you are interested you can display the exact decimal value of any binary floating point number by downloading this FEX submission:
or view the HEX of the binary floating point (note they are exactly the same):
num2hex(a)
num2hex(b)
Summary: how numbers are displayed is not the same thing as how they are stored in memory. Do not confuse the storage of a number with its representation when displayed with a specific format:
If you want to convert to binary you need to specify if you mean:
Which do you want?
0 Comments
Walter Roberson
on 9 Mar 2021
Edited: Walter Roberson
on 9 Mar 2021
And then I want to convert it to binary (only 1.0066 to binary). How can I do that?
a=1.006600000000000
bin = int16(a*2^14)
restored_a = double(bin) / 2^14
restored_a - a
Close enough for rock and roll.
The above handles values in the range -2 (exactly) to 1.99993896484375 . To handle larger ranges you either have to give up negatives, or give up decimal places (current precision is 0.00006103515625), or use more bits.
0 Comments
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!