[Solved] If I have a String containing for example “234” and I want to print it out as “£2.34” How do I do this in Java? [duplicate]


You could use the length of the string as the determinant of whether to format the string using ‘p’ or ‘£’, then use .substring() to get the individual parts of the string (the euros and cents) Here’s an example:

if(string.length() < 3) {
    System.out.println(string+"p");
} else {
    System.out.println("£"+string.substring(0, string.length()-2)+"."+string.substring(string.length-2));
}

What this does is:

If the length of the string is greater than 2, it takes the part before the last 2 digits (using string.substring(0, string.length()-2)) and the second part (string.substring(string.length-2)), separates them with a '.' and precedes everything with a ‘£’, achieving the result ‘£euros.cents’.

1

solved If I have a String containing for example “234” and I want to print it out as “£2.34” How do I do this in Java? [duplicate]