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.
Decimal delimiter depends on current culture preferences:
d.Replace(
System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator,
String.Empty)
will replace '.'
or ','
with ""
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(".","");
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.
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
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
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" };
You could call ToString()
, and then use a regular expression like replacing
"([0-9])\\.([0-9])" with "\\1\\2"
,
which, although still a bit of a hack, would be less fragile than Replace(".","")
Don't try to find a simpler answer to something that's already simple. The easiest way to do it is to use this code:
double dblNumber = 1.5;
string strDouble = dblNumber.ToString("N1").Replace(".","").Trim('0');
If it is something you are going to be doing a lot, wrap it in a function:
string ConvertToString(double dblNumber)
{
return dblNumber.ToString("N1").Replace(".","").Trim('0');
}
精彩评论