简体   繁体   中英

C# Number Format Printing All Significant Digits and Separators

I feel a bit dumb asking this... I need to format a number to show thousands separator, decimal mark, and exactly the precision that is needed to show all significan digits. I have a working solution, but feel there must be a better way:

double myNumber = 1234.56789;
myNumber.ToString("#,##0.#########################################################################################################################"); // see my problem with this?
// will yield "1,234.56789"

I googled both internets from start to end and couldn't find an answer to my problem. Answers on SO like remove trailing zeros and C# String.format a number with dynamic number of significant digits don't respect the thousands separator requirement. And both msdn articles for Standard Numeric Format Strings and Custom Numeric Format Strings have been read and re-read by me without bringing a breakthrough.

My attention was brought to c# how to String.Format decimal with unlimited decimal places? but unfortunately no answer came up with a more concise format string.

What format string would a sane and proficient developer use?

Honestly, I dont see a great problem with your formatting string, so long as you dont repeat it everywhere (put it in a class full of constants, and reuse).

The nearest standard format string is probably along the lines of N50 , but this will display zeros up to the length specified, so your example displays as

1,234.56789000000000000000000000000000000000000000000000

The reason you haven't found the answer you want from Googling is because there's a problem with your question.

Doubles are not stored in decimal form, they're binary numbers. So the concept of a decimal-based "significant digit" doesn't really make sense. As an example, the number 0.1 cannot be represented precisely in binary (much like 1/3 can't be represented precisely in decimal notation).

You could so something like @Jamiec suggested - and it's probably about what you want (although N50 is way overkill, you only get about 17 max significant digits converting a binary to a double). But, you should know that's not really writing out the significant digits. Fundamentally, you can't write out all the significant digits the computer has calculated a number to in decimal, because it calculated it in binary. The computer will have to convert it to decimal first before it writes it out, and that will necessarily cause a loss of precision.

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