开发者

Double to string -- formatter missed?

I have to convert a double to string with the following rules:

  1. If decimal point position is -1 (or another non-existing value meaning 'Auto'), fractional part of the number should be output with all significant digits (all zeroes at the end should be trimmed). If the double is integer, its fractional part shouldn't output at all. For instance, digits = -1: 1029.0 -> 1,029, 1029.123456789 -> 1,029.123456789.

  2. If decimal point position is equal or greater than 0, fractional part of the number should be output with the given number of digits. For instance, digits = 2: 1029.0 -> 1,029.00, 1029.123456789 -> 1,029.12.

  3. Conversion should be culture-dependant (point or comma as decimal point, comma or space as group divider etc).

I have a code for the task:

var _Culture = CultureInfo.CreateSpecificCulture("en-US");
object sourceValue开发者_运维知识库 = 1029.0;//.123456789;

int digits = -1; // 2;

var formatter = "G";
if (digits != -1)
{
    _Culture.NumberFormat.NumberDecimalDigits = digits;
    formatter = "N";
}

var sourceValueAsFloat = (double)sourceValue;
var s = sourceValueAsFloat.ToString(formatter, _Culture);

Is there another formatter (not "N" or "G"), I can use instead? Or, maybe, I can use "N"/"G" another way?

Regards,


See here and here for all the format string specifiers .net understands.


// preferably make allDigits a static field to avoid re-allocating on every call
string allDigits = "#,0." + new string('#', 350);

string output = sourceValue.ToString(
                    digits < 0 ? allDigits : "#,0." + new string('0', digits));

And if you need to handle different cultures explicitly:

string output = sourceValue.ToString(
                    digits < 0 ? allDigits : "#,0." + new string('0', digits),
                    culture);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜