Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double to string with mandatory decimal point

This is probably dumb but it's giving me a hard time. I need to convert/format a double to string with a mandatory decimal point.

1         => 1.0
0.2423423 => 0.2423423
0.1       => 0.1
1234      => 1234.0

Basically, I want to output all decimals but also make sure the rounded values have the redundant .0 too. I am sure there is a simple way to achieve this.

like image 290
wpfwannabe Avatar asked Mar 27 '13 12:03

wpfwannabe


2 Answers

Use double.ToString("N1"):

double d1 = 1d;
double d2 = 0.2423423d;
double d3 = 0.1d;
double d4 = 1234d;
Console.WriteLine(d1.ToString("N1"));
Console.WriteLine(d2.ToString("N1"));
Console.WriteLine(d3.ToString("N1"));
Console.WriteLine(d4.ToString("N1"));

Demo

Standard Numeric Format Strings

The Numeric ("N") Format Specifier

Update

(1.234).ToString("N1") produces 1.2 and in addition to removing additional decimal digits, it also adds a thousands separator

Well, perhaps you need to implement a custom NumberFormatInfo object which you can derive from the current CultureInfo and use in double.ToString:

var culture = CultureInfo.CurrentCulture;
var customNfi = (NumberFormatInfo)culture.NumberFormat.Clone();
customNfi.NumberDecimalDigits = 1;
customNfi.NumberGroupSeparator = "";
Console.WriteLine(d1.ToString(customNfi));

Note that you need to clone it since it's readonly by default.

Demo

like image 199
Tim Schmelter Avatar answered Sep 29 '22 14:09

Tim Schmelter


There is not a built in method to append a mandatory .0 to the end of whole numbers with the .ToString() method, as the existing formats will truncate or round based on the number of decimal places you specify.

My suggestion is to just roll your own implementation with an extension method

public static String ToDecmialString(this double source)
{
    if ((source % 1) == 0)
        return source.ToString("f1");
    else
        return source.ToString();

}

And the usage:

double d1 = 1;
double d2 = 0.2423423;
double d3 = 0.1;
double d4 = 1234;
Console.WriteLine(d1.ToDecimalString());
Console.WriteLine(d2.ToDecimalString());
Console.WriteLine(d3.ToDecimalString());
Console.WriteLine(d4.ToDecimalString());

Results in this output:

1.0
0.2423423
0.1
1234.0
like image 44
psubsee2003 Avatar answered Sep 29 '22 14:09

psubsee2003