Taras
Taras

Reputation: 1128

Insert a dot before last character

is it possible to get a string like "45.6" from an int a = 456; using string.Format?

Upvotes: 2

Views: 3305

Answers (5)

C-va
C-va

Reputation: 2920

You can achieve using IFormatProvider. (Can customize into any format)

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;
            }
        }
    }
}

Upvotes: 0

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23685

Int32 a = 456;

String aString = a.ToString();
aString = aString.Insert((aString.Length - 1), ".")

Upvotes: 0

Levi_vc
Levi_vc

Reputation: 627

        int a = 456;
        String aString = String.Format("{0}{1}{2}", a / 10, ".", a % 10);

Upvotes: 0

mafu
mafu

Reputation: 32710

Divide by 10 (as double).

You need to take the current culture into account, too. To always get a dot, use InvariantCulture.

To avoid floating point imprecision issues (something like 45 -> 4.49999999), make sure to only print the first digit by specifying "0.0" format.

int i = 123;
var s = String.Format (CultureInfo.InvariantCulture, "{0:0.0}", i / 10.0);

Upvotes: 2

Mehmet Ataş
Mehmet Ataş

Reputation: 11559

Math operations may yield different results in different cultures. You may get , instead of .. Try this

var aStr = a.ToString();
var res = aStr.Insert(aStr.Length - 1, ".")

Upvotes: 4

Related Questions