- 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?
25 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Stephen23
2021-3-9
编辑:Stephen23
2021-3-9
"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 个评论
Walter Roberson
2021-3-9
编辑:Walter Roberson
2021-3-9
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!