Reputation: 4999
I have a Double
value and need to find the format string, which converts this value with however many decimals the double value has, as well as with thousand separator.
For example, let's say I have value 1000000.1256. If I don't use any format string, then the default string has full decimals (four digits) but doesn't have thousand separator (1000000.1256
). If I use the standard format string "N", then the output is 1,000,000.13
, i.e., it uses 2 decimals by default and does the rounding. But I don't want it to perform ANY rounding, I want to display 1,000,000.1256
. And please note that I don't know how many decimals the number has, that's why I said I want to display "full" decimals, instead of 2, or 4, or any other larger number of decimals. I know I can do it like this with customize string: "#,#.##########" so it displays up to 10 decimals and it is very unlikely that my numbers have more than 10 decimals. But is this the only/best way?
Upvotes: 0
Views: 104
Reputation: 941317
The notion of "full decimals" is nonsensical. How many full decimals does 10.0 / 3.0 have? There are an infinite number of numbers that are rational but not "perfect". A computer will make it significantly worse, it does math with two fingers instead of ten, turning values like 0.1 into a number with an infinite number of digits.
You are converting numbers to strings for the benefit of a human. Humans are not interested in strings with an infinite number of digits, they tend to tune out after 7. Displaying more than 15 when the variable is of type double is never useful, any digits beyond the 15th are random noise. An inevitable side-effect of computers not having storage for an infinite number of digits.
Create a usable user interface first. If you don't know what is considered "usable" then you have to ask your customers. They do have rules about that in the financial industry, you can't just make up your own.
Upvotes: 3
Reputation: 320
You might need to do extra string operations I believe. It's not a elegant way maybe, but still I think it gives what you need.
double number = 1000000.1256;
string numberStr = number.ToString();
string[] arr = numberStr.Split(',');//my cultureInfo is Turkish so I used ','
string result = Int64.Parse(arr[0]).ToString("0,00", System.Globalization.CultureInfo.InvariantCulture) + "." + arr[1];
result: 1,000,000.1256
Upvotes: 0