Convert int to a string with a specific format

advertisements

I'm trying to convert an classical integer value like:

2000

into a format like this:

2.000,00

I have tried the following methods:

String.valueOf(input.format());

And this method:

private String getCents(Decimal x){
    String y = String.valueOf(x);
    String z = '.';
    if(y.contains(',')) z = ',';
    y = y.substring(0, y.indexOf(z));
    if(x - Decimal.valueOf(y) == 0)
        return String.valueOf(x.format()) + z + '00';
    else return String.valueOf(x.format());
}

But the string class doesn't contains the valueOf method for some reason. Is there any other way to do this ?


The class String does not contain the method valueOf, because this ain't Java, you know. The method you are searching for is ToString, which allows a format-provider as an argument. The simplest way is another string which defines the format.

    int i = 2000;
    Console.WriteLine(i.ToString("#,##0.00"));
    Console.ReadLine();

This will do what you want to do. Read more about format-providers in the docs of the ToStringmethod.