I have double for example 1.890. How I can format like this:
I tried this:
switch (price)
{
case (int)scales.zero:
format = "{0:0}";
break;
case (int)scales.one:
format = "{0:0}";
break;
case (int)scales.two:
format = "{0:000}";
break;
case (int)scales.three:
format = "{0:0000}";
break;
case (int)scales.four:
format = "{0:00000}";
break;
case (int)scales.five:
format = "{0:00000}";
break;
default:
format = "{0:0.00}";
break;
}
if (!string.IsNullOrWhiteSpace(format))
res = string.Format(format, value);
return res;
Your default clause includes a dot: {0:0.00}. Do it like that in the other cases: {0:0.00000} to have 5 zeroes. And divide the number by 100, 1000, etc. before formatting.
First of all, your results are little bit strange, honestly. For example; other than 1
case, all results have decimal separator but for 1
case, it doesn't have any thousand separator. It is okey to solve this but seems strange to me.
Second, I think your double is 1890
rather than 1.890
because when you use your enum values, looks like they divide your double value with their values with powered 10
.
If so, let's define your enum value first.
enum scales
{
zero = 1,
one = 10,
two = 100,
three = 1000,
four = 10000,
five = 100000
}
And second, create a culture that has .
as a decimal separator and has empty string as a thousand separator. For this, let's Clone
a InvariantCulture
and set it's NumberGroupSeparator
to empty string.
var culture = (CultureInfo)CultureInfo.InvariantCulture.Clone();
culture.NumberFormat.NumberGroupSeparator = string.Empty;
Then we can use that culture to format our results using "N"
format specifier and proper precision, after we divide our double value with the enum values that mathes.
double d = 1890;
int price = 1;
string result = "";
switch (price)
{
case (int)scales.zero:
d = d / (int)scales.zero;
result = d.ToString(culture);
break;
case (int)scales.one:
d = d / (int)scales.one;
result = d.ToString("N1", culture);
break;
case (int)scales.two:
d = d / (int)scales.two;
result = d.ToString("N2", culture);
break;
case (int)scales.three:
d = d / (int)scales.three;
result = d.ToString("N3", culture);
break;
case (int)scales.four:
d = d / (int)scales.four;
result = d.ToString("N4", culture);
break;
case (int)scales.five:
d = d / (int)scales.five;
result = d.ToString("N5", culture);
break;
default:
break;
}
Console.WriteLine(result);
You can change the value of price
to 10
, 100
, 1000
, 10000
, 100000
and this will be generate exactly what results do you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.