How to format decimals in a currency format?

I’d recommend using the java.text package: double money = 100.1; NumberFormat formatter = NumberFormat.getCurrencyInstance(); String moneyString = formatter.format(money); System.out.println(moneyString); This has the added benefit of being locale specific. But, if you must, truncate the String you get back if it’s a whole dollar: if (moneyString.endsWith(“.00”)) { int centsIndex = moneyString.lastIndexOf(“.00”); if (centsIndex != -1) { … Read more

How do I format a number in Java?

From this thread, there are different ways to do this: double r = 5.1234; System.out.println(r); // r is 5.1234 int decimalPlaces = 2; BigDecimal bd = new BigDecimal(r); // setScale is immutable bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP); r = bd.doubleValue(); System.out.println(r); // r is 5.12 f = (float) (Math.round(n*100.0f)/100.0f); DecimalFormat df2 = new DecimalFormat( “#,###,###,##0.00” ); … Read more

How can I format a String number to have commas and round?

You might want to look at the DecimalFormat class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57 instead). You also need to convert that string into a number, this can be done with: double amount = Double.parseDouble(number); Code sample: String number = “1000500000.574”; double amount = Double.parseDouble(number); DecimalFormat formatter … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)