how to set precision for double value?  
Author Message
Pockey





PostPosted: Visual C# General, how to set precision for double value? Top

Hi,

double dec = (double)d * 45.00 / 1023.00;

In my application, there is a calcuation gives a double result.

I want to display it on a label. however, the lenght of the double value is too long...

How to set the precision of the double value to 3, such as 3.489 and ignore the other digits.

Is there any choice for the rule as "Smaller than 5, just ignore it; otherwise, add 1 to the last element of the value". I do not know how to explain it in English...

I think this should be a simple problem. However, I searched around and could not find a solution...

Any suggestion for searching such basic information

Thanks a lot!




Visual C#12  
 
 
RizwanSharp





PostPosted: Visual C# General, how to set precision for double value? Top

double dec = (double)d * 45.00 / 1023.00;

label.Text = String.Format("{0:F3}", dec); // Show 3 Decimel Points

I hope this will help! Cheers ;-)



 
 
Pockey





PostPosted: Visual C# General, how to set precision for double value? Top

Thanks RizwanSharp!

So I have to change the double to a string to get the desired precision

Of course it works in this example...However, how to get the double number after setting the precious of it

It seems there does not exist double.Format() or such method...

I hope you can show me more way to get the result, no matter in string form or double form, I want to have a overall impression of how to set a number's precision.

Thanks!



 
 
sirjis





PostPosted: Visual C# General, how to set precision for double value? Top

You can use the Math.Round method, which takes a double (or decimal, which I recommend for precise calculations like in banking) and the precision.

So Math.Round(2.7182818, 3) returns 2.718.

However, Math.Round is defined to round 5's to the nearest even number in the preceding digit, not up, unless you call it like:

Math.Round(2.5, 1, MidpointRounding.AwayFromZero), which returns 3 instead of 2. Note that this variant requires .NET version 2.0.


 
 
RizwanSharp





PostPosted: Visual C# General, how to set precision for double value? Top

The better way to do caclulations is with more Decimels which is the nature of Mathematic but for any reason if you need to round in Float, double or decimel you can use Math.Round; there are also other functions like Math.Ciel() Math.Floor(). The other way is to use them only on your anwers not on the values who are participating in the calculations.

The other thing is always use Decimel datatype for mathematic calculations because float and double will not give you accurate results. You can test it with comparison to the calculator and a simple C# application.

Best Regards,



 
 
Pockey





PostPosted: Visual C# General, how to set precision for double value? Top

Thank you very much!!

I will check that later :)