-2

I have a large float that I want to convert into a string with commas without rounding.

Here is what I have:

String.Format("{0:#,###}", val);

This turns 17154177 into 17,154,180 I would like to keep the commas but not round at the end using c#.

TheProgrammer
  • 1,314
  • 5
  • 22
  • 44
  • 3
    Are you sure this is a ***javascript*** question? – Muhammad Talha Akbar Jul 02 '20 at 21:31
  • 3
    `String.Format` is not a native JavaScript method on the `String` object. Where are you getting that from? You could try [`toLocaleString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString). – chipit24 Jul 02 '20 at 21:32
  • Does this answer your question? [prevent rounding of decimals when using currency string format](https://stackoverflow.com/questions/6042262/prevent-rounding-of-decimals-when-using-currency-string-format) – AndrewL64 Jul 02 '20 at 21:35
  • @AndrewL64 No luck, still rounds at the end – TheProgrammer Jul 02 '20 at 21:38
  • 1
    This smells like a floating point rounding problem, not a string conversion problem. Single-precision floating point values are only precise to [~6 significant digits](https://stackoverflow.com/a/50492868/3791245), but you want precision out to 8 digits. Consider using `decimal` instead of `float`. – Sean Skelly Jul 02 '20 at 21:55

2 Answers2

1

Change your data type to decimal (28-29 significant digits) to have higher precision compared to float (7 digits).

Or you can change it to var. It will let the compiler figure out the best data type to use.

var number = 17154177;
Console.WriteLine(String.Format("{0:#,###}", number));

See this fiddler link, working code

Rod Talingting
  • 943
  • 1
  • 15
  • 25
1

This may be what you're looking for

using System;

class MainClass {
  public static void Main (string[] args) {
    float original = 17154177;

    // 1. Convert the number to a string
    string value = original.ToString("R");

    // 2. Reverse the string
    string reversed = Reverse(value);

    // 3. Add the comma on each third number, backwards
    string formatted = "";
    for(int i = 0; i < reversed.Length; i++) {
      if ((i+1) % 3 == 0) {
        formatted += reversed[i] + ",";
      } else {
        formatted += reversed[i];
      }
    }

    // 4. Reverse it back to the original order
    formatted = Reverse(formatted);

    Console.WriteLine (formatted);
  }

  /* Reverses a string */
  public static string Reverse(string text)
  {
    char[] cArray = text.ToCharArray();
    string reverse = String.Empty;
    for (int i = cArray.Length - 1; i > -1; i--)
    {
        reverse += cArray[i];
    }
    return reverse;
  }
}

I got the reverse method from this question.

diogo.silva
  • 448
  • 4
  • 13