如何在C#中的浮点值?

编程入门 行业动态 更新时间:2024-10-24 20:12:46
本文介绍了如何在C#中的浮点值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个四舍五入浮点值的问题。 我有一个浮点值设置为0.8,但在C#代码它是某种方式0.80000000000000004。

所以我想四舍五入所以它成为0.8。

我已经试过了: $ $ $ $ $ $ $> float roundedFloatvalue =(float)Math 。((十进制)floatvalue,2,MidpointRounding.AwayFromZero);

和:

float roundedFloatvalue =截断(floatvalue,2); public static float Truncate(float value,int digits) { double mult = Math.Pow(10.0,digits); double result = Math.Truncate(mult * value)/ mult; 返回(浮动)结果; $ b $ p $ b

看来,我不能得到0.80000000000000004为0.8,我不知道为什么上面的任何一个都行不通。

解决方案

由于0.8不能用二进制表示浮点。有关此主题的必读信息,请参阅每位计算机科学家应了解的有关Floating-点算术。

您可以使用 decimal 代替使用十进制浮点数的数字正好代表0.8。或者你可以选择继续使用二进制浮点数,但只显示小数点后的有限数字。

要将值存入

十进制decimalValue = Math.Round(十进制)变量,四舍五入到小数点后两位, (十进制)floatValue,2);

I have a problem rounding a float value. I have a float value that is set 0.8 but in the c# code it is somehow 0.80000000000000004.

So i want to round it so it becomes 0.8.

i have tried:

float roundedFloatvalue = (float)Math.Round((Decimal)floatvalue, 2, MidpointRounding.AwayFromZero);

and:

float roundedFloatvalue = Truncate(floatvalue, 2); public static float Truncate(float value, int digits) { double mult = Math.Pow(10.0, digits); double result = Math.Truncate(mult * value) / mult; return (float)result; }

It just seems that i cant get 0.80000000000000004 to be 0.8 and i dont know why any of the above doesnt work.

解决方案

You cannot express 0.8 exactly as a binary floating point value since 0.8 is not representable in binary floating point. Required reading on this topic is What Every Computer Scientist Should Know About Floating-Point Arithmetic.

You might use decimal instead, which represents numbers using decimal floating point and can represent 0.8 exactly. Or you might choose to continue using binary floating point, but only display limited numbers of digits after the decimal point.

To get the value into a decimal variable, rounded to two decimal places, you write:

decimal decimalValue = Math.Round((decimal)floatValue, 2);

更多推荐

如何在C#中的浮点值?

本文发布于:2023-11-16 16:21:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1605894.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浮点   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!