Hi Guys,
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.