0

I'm coding this thing and i would like to add currency but i don't know how to implement the max .99 cent rule

Im using

public static double getBal(Player player){
    if(!PlayerData.getPlayerDataFile(player).contains("Money")){
        return 0.00;
    }
    double bal = PlayerData.getPlayerDataFile(player).getDouble("Money");
    return bal;
}

So if i charge the player some amount it could end up as 2.9333333333 or something how could i fix this?

I charge them with

    public static void setBal(Player player, double newBal){
    PlayerData.setPlayerDataFileValue(player, "Money", newBal);
}
  • Possible duplicate of [How to round a number to n decimal places in Java](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – sinclair May 19 '16 at 03:53
  • Possible duplicate of [Why not use Double or Float to represent currency?](http://stackoverflow.com/q/3730019/5221149) – Andreas May 19 '16 at 04:02

2 Answers2

3

You should use BigDecimal class instead of Double to handle currency.
For example:

BigDecimal money = new BigDecimal("2.9");

UPDATE
I tested it out, it works pretty well:

    String priceStr = "2.9";
    BigDecimal price = new BigDecimal(priceStr);
    System.out.println(price);
    // output 2.9

    priceStr = "2.90";
    price = new BigDecimal(priceStr);
    System.out.println(price);
    // output 2.90

    Double priceDouble = 2.90;
    price = new BigDecimal(priceDouble);
    System.out.println(price);
    // output 2.89999999999999... need to do some rounding

    priceDouble = 2.90;
    price = new BigDecimal(priceDouble).setScale(2, RoundingMode.CEILING);
    System.out.println(price);
    // output 2.90  

Note:
For how to do calculation, there are plenty of tutorials and the documentation is quite clear also, good luck.

Minjun Yu
  • 3,497
  • 4
  • 24
  • 39
1

You can use DecimalFormat and setRoundingMode to round it to two decimal points.

DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.CEILING);

For your code, you could use

DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.CEILING);
double unformattedBal = PlayerData.getPlayerDataFile(player).getDouble("Money");
double bal = df.format(unformattedBal);
return bal;

You could also use the static Math class to handle it:

 double bal = (double) Math.round(unformattedBal * 100d) / 100d;

Oh, and happy first post for me :)

Ark9026
  • 24
  • 2