0

I have a simple question, but it's rather difficult to google. I have an input field for a number, and I need to make this number into a currency. So, if a user inputs 120, I need to format that into $1.20. Then, if they add another digit, say the number becomes 1204, I need to format this as $12.04. I'm using a Double.ParseDouble, but for say 120, this yields $120.00. So, I guess I need something like ParseDouble that will turn a value like 120 into $1.20 instead of $120.00. How do I do this?

1
  • 5
    Did you tried something obvious like dividing by 100? Of course double 100. Commented Oct 19, 2015 at 21:37

3 Answers 3

1

use Double.parseDouble(double number);, but easily multiply with 0.01 :)

Then you have your currency and everything is fine ;)

Devlen

Sign up to request clarification or add additional context in comments.

Comments

0

You can do it without even parsing in a numeric.

Use a StringBuilder object to do so:

    String input = "120";
    String output = new StringBuilder(input).insert(input.length() - 2,".")
                                            .insert(0, "$").toString();
    System.out.println(output); // Prints $1.20

1 Comment

This is exactly what I was looking for. Thx.
0
public String getNumberCurrency(double number){

 NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.getDefault());
 String moneyString = formatter.format(number/100);
 return moneyString;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.