Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# formatting a number with thousand separators but keeping the decimal places count as is

I want to add a thousands separator to a double number but want to keep the decimal places as is i.e. dont want any rounding.

#,# is solving my problem of adding the thousand separator but how do I preserve the decimal places ? #,# strips off the part after ..

I cannot use any culture or something like that & the developer whose function I am calling has only given me a way of changing the format by passing as parameter strFormat.

I did check other posts & even the docs but somehow not able to figure this out.

string strFormat = "#,#";
string str = double.parse("912123456.1123465789").ToString(strFormat);
 //Expected here 912,123,456.1123465789 
//Actual Output 912,123,456

//912123456.123 should give 912,123,456.123
//912123456.1 should give 912,123,456.1
//912123456.1123465789 should give 912,123,456.1123465789
//912123456 should give 912,123,456
like image 937
Abdul Rehman Sayed Avatar asked Sep 16 '25 13:09

Abdul Rehman Sayed


2 Answers

If you know the max number of decimal places, e.g. 10, then use:

string strFormat = "#,#0.##########";

Update:

This max number is known. According to Microsoft documentation a Double value has up to 15 decimal digits of precision (including both before and after the decimal point). More than 15 digits will be rounded.

So if you must invoke that method of 'double.parse' and can only send the format, this is the best you can do:

string strFormat = "#,#0.###############";
like image 94
Udi Y Avatar answered Sep 19 '25 01:09

Udi Y


You can calculate the formatting dynamically for each number:

public static void Main()
{
    var number = 1234.12312323123;

    var format = GetNumberFormat(number);
    Console.WriteLine(number.ToString(format));
}

public static string GetNumberFormat(double number)
{
    var numberAsString = number.ToString();

    var decimalPartSize = numberAsString.Substring(numberAsString.LastIndexOf('.') + 1).Length;

    return $"N{decimalPartSize}";
}

So

number = 1234.12312323123

will give you 1,234.12312323123. Works for negative numbers as well. Also, as we work with strings, there won't be any rounding errors or precision artifacts.

like image 40
zhulien Avatar answered Sep 19 '25 01:09

zhulien