Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

.net - Why is modulus operator not working for double in c#?

Consider this:

double x,y;
x =120.0;
y = 0.05;

double z= x % y;

I tried this and expected the result to be 0, but it came out 0.04933333.

However,

x =120.0;
y = 0.5;
double z= x % y;

did indeed gave the correct result of 0.

What is happening here?

I tried Math.IEEERemainder(double, double) but it's not returning 0 either. What is going on here?

Also, as an aside, what is the most appropriate way to find remainder in C#?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because of its storage format, doubles cannot store every values exactly as is is entered or displayed. The human representation of numbers is usually in decimal format, while doubles are based on the dual system.

In a double, 120 is stored precisely because it's an integer value. But 0.05 is not. The double is approximated to the closest number to 0.05 it can represent. 0.5 is a power of 2 (1/2), so it can be stored precisely and you don't get a rounding error.

To have all numbers exactly the same way you enter / display it in the decimal system, use decimal instead.

decimal x, y;
x = 120.0M;
y = 0.05M;

decimal z = x % y;  // z is 0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...