0

So I have kinda helper with this code which I use everywhere in system where I need to round a double:

public static double Round(double source)
{
    return Math.Round(source, Program.AppSettings.DigitAfterComma);
}

The idea is to round any input double to double with some character after comma which is read from file. I use it in my services with calculations and in my ViewModels and .cshtml for results render.

The problem is that dealing with calculations is OK, but when I need to render doubles like 15.0% I get only 15% as output. It will be hard to write 2 methods for renderer and for calculations because this method has a numerous references all over the system.

Is there any way to get xx.0 everytime I call the method without formatting it to string because I need double type output for calculations?

AfanEvgOda
  • 15
  • 1
  • 3
  • Well, `15.00 == 15.0 = 15`; your want *different representation* of the *same* value - `string result = value.ToString("F1");` Another possibility is to switch from `double` to `decimal`: `decimal value = value 15.0M;` then `result = value.ToString();` will return `15.0` – Dmitry Bychenko Jul 03 '18 at 09:38
  • Ok so is overriding a double.ToString() method will be a "good" idea and will it work for rendering double values on .cshtml ? – AfanEvgOda Jul 03 '18 at 09:41
  • `ToString()` has been specially designed for string representation of the object (`double` in your case). That's why `ToString()` is quite natural choice. – Dmitry Bychenko Jul 03 '18 at 09:45
  • It's only when you convert a `double` to a string that you get any formatting. – Enigmativity Jul 03 '18 at 09:47
  • 1
    Rounding and formatting are different things. You should not round a number just to "format" it to a certain number of digits. You should be [formatting it](https://stackoverflow.com/questions/12146100/string-format-for-only-one-decimal-place), using [numeric formatting codes](https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings) passed to `ToString()` or appended to a replacement parameter in `string.Format()`. If you round the number you are losing information and as you have discovered the default formatter doesn't always do what you want it to do. – John Wu Jul 03 '18 at 09:48
  • Thanks a lot, Dmitriy, your recomendations look like solve my problem. If you could like copy-past your comment with result solution I could mark your answer as correct. Now I really see that my solution for rounding everything in one place for rendering and calculations was a really dumb idea – AfanEvgOda Jul 03 '18 at 09:49
  • @AfanEvgOda - There are very few times that `Math.Round(` is worth calling. – Enigmativity Jul 03 '18 at 09:58
  • If it's just a formatting issue you could use p = 12; var a = p.ToString("0.00"); alfer the call to the round function – Gianluca Conte Jul 03 '18 at 09:58

0 Answers0