Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

c# how to String.Format decimal with unlimited decimal places?

I need to convert a decimal number to formatted string with thousand groups and unlimited (variable) decimal numbers:


    1234 -> "1,234"
    1234.567 -> "1,234.567"
    1234.1234567890123456789 -> "1,234.1234567890123456789"

I tried String.Format("{0:#,#.#}", decimal), but it trims any number to max 1 decimal place.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use # multiple times (see Custom Numeric Format Strings):

string.Format("{0:#,#.#############################}", decimalValue)

Or, if you're just formatting a number directly, you can also just use decimal.ToString with the format string.

However, there is no way to include "unlimited decimal numbers". Without a library supporting arbitrary precision floating point numbers (for example, using something like BigFloat from Extreme Numerics), you'll run into precision issues eventually. Even the decimal type has a limit to its precision (28-29 significant digits). Beyond that, you'll run into other issues.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...