将数字对象转换为格式化数字
Converting object that is a number into formatted number
如何将 object
转换为 string
并应用数字格式?传递的对象是数值。
我试过了
private string FormatValue(string field, object[] values)
{
result = string.Format("n1", values[0]);
}
但这将给出 n1
作为结果,而不是格式化的数值。
我想得到一个格式化的数值。例如传递12345
,我想得到12 345.0
.
使用
string.Format("{0:n1}", values[0]);
如果传递的值不是数字而是字符串,您需要先解析它(f.e。Convert.ToDecimal
)。
怎么样:
object value = values[0]; // why an array for one value?
if(value is IFormattable) {
return ((IFormattable)value).ToString("n1", CultureInfo.CurrentCulture);
} else {
return value?.ToString();
}
使用
result = values[0].ToString("n0")
使用字符串插值可以这样写:
private string FormatValue(string field, object[] values)
{
return $"{Convert.ToDecimal(values[0]):n1}";
}
你似乎想根据你的示例数据(整数)做这样的事情:
private string FormatValue (object value)
{
//You can amend this check to another numeric type or add others
if (value is int)
{
return string.Format("{0:n1}", value);
}
else
{
throw new System.ArgumentException("object not an integer", value);
}
}
如何将 object
转换为 string
并应用数字格式?传递的对象是数值。
我试过了
private string FormatValue(string field, object[] values)
{
result = string.Format("n1", values[0]);
}
但这将给出 n1
作为结果,而不是格式化的数值。
我想得到一个格式化的数值。例如传递12345
,我想得到12 345.0
.
使用
string.Format("{0:n1}", values[0]);
如果传递的值不是数字而是字符串,您需要先解析它(f.e。Convert.ToDecimal
)。
怎么样:
object value = values[0]; // why an array for one value?
if(value is IFormattable) {
return ((IFormattable)value).ToString("n1", CultureInfo.CurrentCulture);
} else {
return value?.ToString();
}
使用
result = values[0].ToString("n0")
使用字符串插值可以这样写:
private string FormatValue(string field, object[] values)
{
return $"{Convert.ToDecimal(values[0]):n1}";
}
你似乎想根据你的示例数据(整数)做这样的事情:
private string FormatValue (object value)
{
//You can amend this check to another numeric type or add others
if (value is int)
{
return string.Format("{0:n1}", value);
}
else
{
throw new System.ArgumentException("object not an integer", value);
}
}