C# Decimals rounding off

Hemanth B 886 Reputation points
2021-05-26T14:43:26.18+00:00

Hi, I created a Temperature Converter with C# Win form application.

In that I added options to Users that they can convert Fahrenheit to Celsius and vice versa

So, 1 Fahrenheit = -17.222222222222222 Celsius right?
So, when they select "Fahrenheit to Celsius" and click on "Convert" a text box will appear below with the answer.

Example:
If they select " 1 Fahrenheit to Celsius" and click on "Convert", the text box gives the answer as -17.222222222222222
If they select " 2 Fahrenheit to Celsius" and click on "Convert", the text box gives the answer as
-16.6666666666667
But having so many decimal places will not look good.
So I want only the decimal places to reduce in number.
Example: The answer should reduce from -17.222222222222222 to -17.22222 (having only five or less decimal places). Which means that which ever input they give like " 2 Fahrenheit to Celsius" or " 3 Fahrenheit to Celsius", I want the only decimal places to reduce in number.

Is there any way to do that? Below is my code.

99898-screenshot.png

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,161 Reputation points
    2021-05-26T15:55:00.783+00:00

    Personally I would strongly recommend that you don't use Convert unless you are dealing with an actual object. For string parsing always use the appropriate primitive's Parse method.

    var text = "2";
    
    var fahrenheit = Double.Parse(text);
    var celsius = (fahrenheit - 32) * 5.0 / 9.0;
    
    var result = celsius.ToString("#.#####");       
    Console.WriteLine($"{celsius} = {result}");
    

    However you'll notice that ToString will always round the value which based upon your post title is what you don't want. Therefore you'll need to use a workaround. One workaround is to use Microsoft.VisualBasic.Strings.FormatNumber which allows truncation.

    Another workaround is to do the truncation yourself. Depending upon the version of the framework/core you're using there is Math.Round and Math.Truncate to help. Alternatively you could use a calculation like Math.Floor(precision * value) / precision or convert the value to the string with one extra digit of precision and then remove the last digit (if the resultant string is using the full precision).


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.