0

Here is a string format which formats a number up to 2 decimal places and if there are no decimal places then it will show the simple integer itself:

String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.0);         // "123"

so {0:0.##} will do the job. But I need to have a thousand separator on integer part. so something like 1234.456 should be like 1,234.45. I know {0:n0} will do a thousand separators but how to combine it with the decimal place formatter?

Inside Man
  • 4,194
  • 12
  • 59
  • 119
  • no, it is not working – Inside Man May 12 '19 at 19:09
  • Does [this](https://stackoverflow.com/a/42419283/589259) work? It should keep to the locale, which the current answer doesn't. – Maarten Bodewes May 12 '19 at 19:13
  • @MaartenBodewes Are you talking about my answer, and if so, what does it mean to keep to the locale? – GSerg May 12 '19 at 19:15
  • Well, if I looked at the other answers there, the comma and dot are now strictly used for thousands and decimals. That's not correct e.g. here in NL, where the dot is the thousands separator and the comma denotes the decimals. – Maarten Bodewes May 12 '19 at 19:18
  • @MaartenBodewes In a format string, the comma is a placeholder for the locale's thousands separator, and the dot is a placeholder for the locale's decimal dot. You will have different output with the same format string on different locales. – GSerg May 12 '19 at 19:19
  • OK, then I guess quite a few of the comments on the other Q/A are off :) – Maarten Bodewes May 12 '19 at 19:20

1 Answers1

4
String.Format("{0:#,##0.##}", 123.0);
GSerg
  • 76,472
  • 17
  • 159
  • 346
  • What does this do for numbers over 9,999? Why is there a zero after the `#`? Currently this is a code only answer. – Maarten Bodewes May 12 '19 at 19:31
  • 1
    @MaartenBodewes The zero is there because it was originally there and I just prepended the `#,##`. For numbers over 9999 it's going to repeat the thousand separator pattern and insert one after each 3 digits. – GSerg May 12 '19 at 19:33
  • @GSerg Great Man, thank you. Could you please introduce some resources to study about string formatting? – Inside Man May 12 '19 at 19:47
  • @InsideMan The only one I've even needed is https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting, from which you follow to https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings for numbers specifically. – GSerg May 12 '19 at 19:49