开发者

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

开发者 https://www.devze.com 2023-04-12 21:59 出处:网络
I got: int number = 1255; -> //It could also be 125(1€25Cent) or 10(10Cent) or 5(5Cent) publi开发者_如何转开发c double toMoney(int number)

I got:

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

publi开发者_如何转开发c 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?


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.


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.


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.


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.


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.


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号