Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intelligently & safely convert a Double to String?

Trying not to repeat myself (to be DRY) here, help me out. =)

I have a double which represents a rating / 5.

The possible values are:

0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5.

I want to convert this to a string without the decimal place.

So the values would become:

"0", "05", "1", "15", "2", "25", "3", "35", "4", "45", "5".

Why am i doing this? Because i'm trying to dynamically create a link based on the value:

string link = "http://somewhere.com/images/rating_{0}.gif";
return string.Format(link, "15");

The possible values are handled/validated elsewhere, in other words i can be 100% sure the value will always be one of those i mentioned.

Any ideas? Some special format i can use in the .ToString() method? Or am i stuck with an un-DRY switch statement? Or can i cheekily do a decimal.ToString().Replace(".","")?

EDIT:

Whoah, thanks for all the answers guys! =)

Most answers are correct, so i'll leave this open for a day or so and pick the answer with the most votes.

Anyway, i ended up creating a simple extension method:

public static string ToRatingImageLink(this decimal value)
    {
        string imageLinkFormat = "http://somewhere.com/images/rating_{0}.gif";
        return string.Format(imageLinkFormat, value.ToString().Replace(".0", string.Empty).Replace(".", string.Empty);
    }

Guess it was a case of "KISS" and "DRY". In this case the syntactic sugar of extension methods kept it DRY, and and the actual one-line implementation satisfies KISS.

like image 660
RPM1984 Avatar asked Jul 26 '10 05:07

RPM1984


6 Answers

Decimal delimiter depends on current culture preferences:

d.Replace(
    System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator,
    String.Empty)

will replace '.' or ',' with ""

like image 78
abatishchev Avatar answered Nov 15 '22 06:11

abatishchev


If you could live with strings like 00, 05, 10, 15, 20 ... etc., you could simply use

(rating * 10).ToString("00")

If not, use InvariantCulture as argument to ToString in order to force the use of a decimal point (".") in all countries (in Germany the default would be "," for example):

rating.ToString(CultureInfo.InvariantCulture).Replace(".","");
like image 44
MartinStettner Avatar answered Nov 15 '22 05:11

MartinStettner


I would just use the "cheekily" method you describe at the end. In pure semantics of the thing, you're manipulating a string, not the actual number, so I think a string replacement would be exactly the correct prescription here.

If you really want to overcomplicate it, consider creating a new IFormatProvider for this situation. This would be a better way of catching potential errors, but it adds a layer of complexity.

like image 33
drharris Avatar answered Nov 15 '22 04:11

drharris


you can just use Replace(".", string.Empty); with no need for Replace(".0", string.Empty)

check the below code

double[] x = { 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5 };
            foreach (var item in x)
            {
                listBox1.Items.Add(item.ToString().Replace(".", string.Empty));
            }

the result will be alt text

like image 41
Amr Badawy Avatar answered Nov 15 '22 05:11

Amr Badawy


Use a hashtable/dictionary and keep mappings from double to string in there. That will be much more robust and simpler than parsing your double

like image 1
Nitin Chaudhari Avatar answered Nov 15 '22 06:11

Nitin Chaudhari


To avoid messing with decimal formats, I would format the whole part as an integer and use an array lookup for the fractional part:

public static string ToRatingImageLink(this decimal value)
{
    string imageLinkFormat = "http://somewhere.com/images/rating_{0}{1}.gif";
    int index = decimal.ToInt32(decimal.Round(value * 2));
    return string.Format(imageLinkFormat, index / 2, Suffix[index % 2]);
}

static readonly string[] Suffix = { "", "5" };
like image 1
finnw Avatar answered Nov 15 '22 04:11

finnw