-1

As I understand from Microsoft's documentation, if I have 340550.46 and I apply the format string #,##0.00 I should get the string "340,550.46". But instead, I'm getting "340.550,50". I've set breakpoints to ensure that I know what the number and format strings are going in.

To be more specific, I have a string "340550.46", and I convert it to a float, and then use ToString() to format it with "#,##0.00":

float.Parse("340550.46").ToString("#,##0.00)

What am I doing wrong here? Why is it rounding the number, and what can I do to prevent that?

Lisa
  • 23
  • 3
  • 2
    Is your question about the [rounding](https://stackoverflow.com/a/21688396/11683) or the [decimal comma](https://stackoverflow.com/q/23156197/11683)? – GSerg Oct 11 '22 at 18:50
  • 5
    `float` or `Single` are limited to 7 signfiicant digits, which would be 345550.5. Change the type to `double` for up to 16 significant digits. – Rick Davin Oct 11 '22 at 18:52
  • 1
    The final output is subject to your Locale settings. There's an overload that allows you to specify the locale you wish. Not sure whether a duplicate because not sure yet what you're asking https://stackoverflow.com/questions/2341677/format-decimal-to-string-in-correct-culture-info – Eric J. Oct 11 '22 at 18:53
  • 3
    @RickDavin: Two digits after the decimal place could well be money, in which case `decimal` is more appropriate. – Eric J. Oct 11 '22 at 18:55
  • @RickDavin, can you put that as an answer and I'll mark it right? Also, I'm an idiot. – Lisa Oct 11 '22 at 19:30
  • For future questions please re-read [mre] guidance on posting code - the current code in the question unnecessarily combines two steps into a single line making it harder for everyone (and you in particular) to understand the issue. Separating paring and formatting would let you see what specific step causes problem you don't understand. I.e. "why `340550f +.46f` is 340550.5" could be a way to ask about part you don't understand. – Alexei Levenkov Oct 11 '22 at 20:29

1 Answers1

1

The reason for the rounding is that a float is limited to 7 signficant digits.

See: https://en.wikipedia.org/wiki/IEEE_754

If you changed to a double, you would get that 8th extra digit. Also, if you are formatting to 2 decimal places since it may be currency, consider using Decimal.

Rick Davin
  • 1,010
  • 8
  • 10