How can i insert a decimal point into either an integer or a String(probably a String), 2 decimals from the right? like with money?

eg/ 13922
139.22

Recommended Answers

All 5 Replies

You can construct a stringbuffer from the string you want to modify, then use the insert method to insert a "." in the desired place. Then use the stringbuffer's toString() method to convert it back to a string. You can't put decimals in integers.

I've had a look at that class and thank you its exactly what im looking for but what syntax would i use to insert 2 from the right? i cant find it in the api

like String length and then -2?

Why don't you just use the package ......
import java.text.NumberFormat;

then use this in the body.......
NumberFormat money = NumberFormat.getCurrencyInstance();

lastly print out in the body .......
System.out.println(money.format(dollars));

Idk if this is what you were looking for, but this is a very simple version of getting the 2 decimal places.

You could do as mentioned above (use the number format class).

However you could also do this using String functions (length, and substring)

int length = inputString.length();
        String beforeDecimal = inputString.substring(0,length - 2);
        String formatted = beforeDecimal + "." + (inputString.substring(length - 2));
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.