1

是否可以从int a = 456;使用 string.Format 中获取类似“45.6”的字符串?

4

5 回答 5

3

数学运算在不同的文化中可能会产生不同的结果。你可能会得到,而不是.. 尝试这个

var aStr = a.ToString();
var res = aStr.Insert(aStr.Length - 1, ".")
于 2013-01-15T12:59:06.140 回答
2

除以 10(作为两倍)。

您还需要考虑当前的文化。要始终获得一个点,请使用InvariantCulture.

为避免浮点不精确问题(例如 45 -> 4.49999999),请确保通过指定“0.0”格式仅打印第一个数字。

int i = 123;
var s = String.Format (CultureInfo.InvariantCulture, "{0:0.0}", i / 10.0);
于 2013-01-15T13:03:53.490 回答
0
        int a = 456;
        String aString = String.Format("{0}{1}{2}", a / 10, ".", a % 10);
于 2013-01-15T13:19:47.720 回答
0
Int32 a = 456;

String aString = a.ToString();
aString = aString.Insert((aString.Length - 1), ".")
于 2013-01-15T13:25:21.670 回答
0

您可以使用 IFormatProvider 来实现。(可以定制成任何格式)

int val = 456;  
string s = string.Format(new CustomerFormatter(),"{0:1d}", val);
string s1 = string.Format(new CustomerFormatter(), "{0:2d}", val);
Console.WriteLine(s); //45.6
Console.WriteLine(s1); //4.56

 public class CustomerFormatter : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;
        else
            return null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (!this.Equals(formatProvider))
        {
            return null;
        }
        else
        {
            string customerString = arg.ToString();
             switch (format)
            {
                case "1d":
                    return customerString.Insert(customerString.Length - 1, ".");
                case "2d":
                    return customerString.Insert(customerString.Length - 2, ".");

                default:
                    return customerString;
            }
        }
    }
}
于 2013-01-15T13:14:50.053 回答