0

I am trying to change the format of an object which can either be an integer or a decimal to add commas (eg., 1000 to be returned as 1,000) using below custom formatter

string temp => $"{value:n0}"

The above works fine but when the value is decimal, it removes decimal points so I came up with below format which retains decimals when the value is decimal but commas are not returned

string temp => $"{value:.#}"

May I know a better way to do this such that below results are obtained?

1000 to be returned as 1,000
13.00 to be returned as 13
13.1 to be returned as 13.1

I only want to include decimals only when they are non zero

DoIt
  • 3,270
  • 9
  • 51
  • 103
  • Why use `n0` if you want decimal points? Why not `n1` ? – Panagiotis Kanavos May 09 '17 at 15:35
  • @PanagiotisKanavos when I use n1, it always returns decimal points which fails the second case I mentioned (13.0 ->13) – DoIt May 09 '17 at 15:38
  • Possible duplicate of [format a number with commas and decimals in C# (asp.net MVC3)](http://stackoverflow.com/questions/16035506/format-a-number-with-commas-and-decimals-in-c-sharp-asp-net-mvc3) – Vassalware May 09 '17 at 15:39
  • @NickWilson I am not exactly sure if its a duplicate as mentioned in the previous comments, I would like to exclude decimal points which are zeroes – DoIt May 09 '17 at 15:39
  • 2
    @NickWilson not a duplicate. The linked question essentially asks for `n2`. The OP wants to prevent decimals if the input doesn't contain any – Panagiotis Kanavos May 09 '17 at 15:40

1 Answers1

2

There is no standard format that will return 0 decimals for integral/types values. You can use the #,###.# format to return a string that uses groupind and decimal separators with optional decimal digits. You'll have to specify the number of decimals explicitly.

The line :

Console.WriteLine($"{d:#,###.#}");

Returns strings in the form you specified:

1000       -> 1,000
13         -> 13
13.1       -> 13.1
1234567.8  -> 1,234,567.8
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • I am assuming the above code returns 13.0 as 13 instead of 13.0 – DoIt May 09 '17 at 15:52
  • Is there a typo in your last example? Should that have been the multiple decimal places on the left being rounded on the right? – Chris May 09 '17 at 15:52
  • @Dev: There is no difference between 13.0 and 13. They are the same number and will only ever be displayed differently when converted to a string. So yes, 13.0 will return 13, the same as 13 would. – Chris May 09 '17 at 15:53
  • @Chris you are right, I was experimenting with two decimals when I tried `1234567.89` – Panagiotis Kanavos May 10 '17 at 07:44