eMi
eMi

Reputation: 5628

Java - How to get the double from an Integer (Money)

I got:

int number = 1255; -> //It could also be 125(1€25Cent) or 10(10Cent) or 5(5Cent)

public double toMoney(int number)
{
...
}

as return, I want the double number: 12.55 or if input: 10 then: 00.10

I know that I can do with Modulo something like this:

1255 % 100.. to get 55.. But how to do it for 12 and at the end, how to form it as a double?

Upvotes: 2

Views: 2983

Answers (6)

dragn
dragn

Reputation: 1050

The way printing money amounts should be done is by using NumberFormat class!
Check out this example:

NumberFormat format = NumberFormat.getCurrencyInstance(Locale.FRANCE);
format.setCurrency(Currency.getInstance("EUR"));
System.out.println( format.format(13234.34) );

Which print this output:

13 234,34 €

You can try different locales and currency codes. See docs: http://download.oracle.com/javase/1.4.2/docs/api/java/text/NumberFormat.html.

Upvotes: 4

Mysticial
Mysticial

Reputation: 471529

If I'm understanding your question correctly, you're probably trying to just do this:

return (double)number / 100.;

Though a word of warning: You shouldn't be using floating-point for money due to round-off issues.

If you just want to print the number in money format, here's a 100% safe method:

System.out.print((number / 100) + ".");
int cents = number % 100;
if (cents < 10)
    System.out.print("0");
System.out.println(cents);

This can probably be simplified a lot better... Of course you can go with BigDecimal, but IMO that's smashing an ant with a sledgehammer.

Upvotes: 3

Michael Borgwardt
Michael Borgwardt

Reputation: 346476

That method should not exist, because it cannot give correct results.

Because internally, double is a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all. Read the Floating-Point Guide for more information.

If you need decimals, your output format should be BigDecimal or String.

Upvotes: 5

pabdulin
pabdulin

Reputation: 35255

public double toMoney(int number)
{
    return number / 100.0;
}

P.S. You shouldn't use double for money values, bad idea.

Upvotes: 2

Cory Kendall
Cory Kendall

Reputation: 7324

public double toMoney(int number)
{
return number / 100.0
}

The trick is to use 100.0 rather than 100 to force java to use double division.

Upvotes: 2

NPE
NPE

Reputation: 500873

public double toMoney(int number)
{
  return number / 100.0;
}

If you're dealing with monetary amounts, do bear in mind that some loss of precision can occur when you convert the number to a double.

Upvotes: 2

Related Questions