Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How to keep the data after decimal point in double array division in C#
How to keep the data after decimal point in double array division in C#
By default, division in c# does not retain decimal points.

Decimal result =100/1000; //Result = 0;

You need to keep decimal points, which can be as follows

Decimal result =100m/1000;

M stands for decimal system.

What if it is a variable? This requires mathematics. Circle ()

int x = 120;

int y = 100000;

Decimal result = (decimal) x/y; // (decimal)x/ y means to convert x into a decimal and then divide it. If you divide by int, you will lose the decimal point.

But there are too many numbers after the decimal point, which need to be processed. At this time, mathematics. Round () is required.

Decimal result = math. Round ((decimal) x/ y, 2); The following 2 means to keep 2 decimal places.

-

In the C# sum method, the type of the value obtained by dividing by "/"is related to the types of its divisor and dividend. For example:

int a = 4;

int b = 5;

Floating c = a/b;

The result is 0 (because the int will be divided first and the result will be 0, and then the result will be converted to float 0;; );

In a word, the numbers obtained are all plastic, and finally it is found that the type of the value obtained after division is related to the types of his divisor and dividend. Therefore, it should be written like this:

Floating point a = 3;;

Floating point b = 5;;

Floating c = a/b;

Only in this way can we draw the correct conclusion!

In int, 2/5 results in 0.

And because the left side of the expression (float num = 2/5) is float, and int can be converted into float implicitly, C# changes 0 to float: 0.0.

If you want to get the correct result, you must add at least one number to the right of the equal sign: add a decimal point or add f:

2.0/5

or

2.0/5.0

or

2f / 5

I hope it helps you!