Decimal and double Type Error

Source: Internet
Author: User

Int A = (INT) (19.9*100); // 19.9 The default value is double.
Int B = (INT) (19.9 m * 100); // converts 19.9 to decimal type

Console. writeline (a); // output: 1989

Console. writeline (B); // output: 1990

 

Needless to say,. net, C # is to use Java to estimate this result. This result is inevitable.
19.9 is represented as a double type. The binary format is:
1 00000000110 011111001100110011001100110011001100110011001100110
(Note the two spaces in the middle. If you don't know what it means, check the double memory representation)
However, the result of the 19.9*100 binary operation is
1 00000010011 111000101111111111111111111111111111111111111111111
Since there are n 11111 s in the end, I guess the overflow may have been exceeded by the computer.
So this number is a little less than 1990 (probably 1989 ...)
However, your Integer Operation directly truncates the following number, so it becomes 1989.
As for why do you say that 9.9 29.9 is not the case, it is possible that there is no overflow (do not use a 10-digit thinking to guess the binary)
In other languages, you can only achieve this by retaining higher accuracy and rounding them apart. C # specifically introduces abnormal decimal types to support financial computation, so your problem can be solved through decimal now (decimal has a very high precision, which may be as high as dozens of floors... enough)
Binary numbers cannot accurately represent floating-point numbers. decimals are generally labeled with approximate values. So there will be so many 19.9 of the 100*11111111 binary identifiers. The (INT) (19.999999999) result is the result of directly truncating the decimal point, so 1989.999999 is 1989. But why is decimal correct? because it does not have a real decimal storage base, and all the numbers are on the right of the decimal point. Then how does it store decimals? The answer is the proportional factor. Of course, there are symbols.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.