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
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.###############";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With