简体   繁体   中英

How to convert a big float into a string with commas without rounding

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#.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM