Floating-point float data cast to int integral type

Source: Internet
Author: User

Problem: The following code wants to get the size of a quotient between a number of two decimal types, and the results occasionally go wrong (note that occasionally)

Decima T1;

Decima T2;

int Shang =convert.toint32 (t1/t2);

WORKAROUND: You will have a rounding process when casting the decimal type data to an int integral type. As below, you need to use the Math.truncate method to take the integer digits. So it is necessary to use this method to take the whole

Problem code:

Decima T1=1.2m;

Convert.ToInt32 (T1) got 1

Decima t2=1.7m;

Convert.ToInt32 (T2) got 2

After changing to the following code:

Decima T1=1.2m;

Convert.ToInt32 (math.truncate (T1)) gets 1

Decima t2=1.7m;

Convert.ToInt32 (Math.truncate (T2)) gets 1

Floating-point float data cast to int integral type

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.