开发者

.NET Rounding Help

I have 10 fractional numbers (double type) that add up to 1. My client wants to show one decimal place in our grid and I've tried using the decimal data type, Math.Round (Away and Even), but I just can't get the numbers to add up to 1 (.98). My math skills are lacking and I can't figure out how to do this correctly. Any help would be 开发者_运维技巧great!

0.429068150 0.222531293 
0.091098748 0.062586926
0.053546592 0.047983310
0.031988873 0.024339360
0.022948540 0.013908206


The numbers seem to add up to something very close to one as-is.

If I'm understanding you correctly, you want to round a bunch of numbers for display purposes but still be able to do math on them and get the results you would've seen if you had not rounded them.

So to illustrate the problem real quick: 1.5 + 2.5 = 4, whereas 1 + 2 = 3. Rounding changed the numbers and that changed the result.

What you could do is display them in the grid rounded however you want, but keep the high fidelity (unrounded) version of the numbers behind the scenes, and do your totaling on that.


They add up to 0.999999998000000. You're probably looking for format strings. You can set them in your column's properties. (Without knowing exactly what you're using, I can't help further with where to place the format string.)

double i = 0.42906815+0.222531293+0.091098748+0.062586926+0.053546592+0.04798331+0.031988873+0.02433936+0.02294854+0.013908206;
Console.WriteLine(string.Format("{0:N1}", Math.Round(i,1)));

That prints 1.0. Notice the {0:N1}. That says print the number with one decimal place.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜