简体   繁体   English

在C#中划分2个浮点数时增加精度

[英]Adding precision while dividing 2 floats in C#

I am trying to write a piece of code in C# which divides 2 floats and returns the results upto 6 decimal places. 我试图用C#编写一段代码,该代码将2个浮点数相除,并将结果返回最多6个小数位。 Here is the code that i have written. 这是我编写的代码。 Problem is I get the results as 0.6 instead of 0.60000. 问题是我得到的结果是0.6而不是0.60000。 Please advice a possible a solution to this. 请提出可能的解决方案。

Here is the code : 这是代码:

float probability=((float)counter/(float)(max+N));
probability = probability * (float)1.000000;                
Console.WriteLine("Probability:{0:N6}",probability.ToString());

You should not use ToString to specify the values to use for the string format. 您不应使用ToString来指定用于字符串格式的值。

After calling ToString , the second argument to WriteLine becomes the string "0.6" . 调用ToStringWriteLine的第二个参数变为字符串"0.6" The format here is ignored because the runtime is only just evaluating the expression probability.ToString() . 此处的格式将被忽略,因为运行时仅在评估表达式probability.ToString() To fix this, remove .ToString because you want the second argument to be treated as a float : 要解决此问题,请删除.ToString因为您希望将第二个参数视为float

Console.WriteLine("Probability:{0:N6}",probability);

I think what you want is Console.WriteLine("Probability: {0:0.000000}", probability) . 我认为您想要的是Console.WriteLine("Probability: {0:0.000000}", probability) See https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings for details. 有关详细信息,请参见https://docs.microsoft.com/zh-cn/dotnet/standard/base-types/custom-numeric-format-strings

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM