This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes BigDecimal money format chop off to 2 decimal Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "BigDecimal money format chop off to 2 decimal" Watch "BigDecimal money format chop off to 2 decimal" New topic
Author

BigDecimal money format chop off to 2 decimal

Adam Lim
Greenhorn

Joined: Mar 13, 2007
Posts: 5
hi. i wanna to money format with 2 decimal.
if no decimal, just append . 2 zero.
if 3 or more decimal. just chop off instead of rounding up.

output :-
//1727 => 1727.00
//1727.1 => 1727.10
//1727.23 => 1727.23
//1727.236 => 1727.23
//1727.231 => 1727.23
-------------------------------------------------------------------------------------
import java.math.BigDecimal;

public class TestBigDecimal {

public static void main(String[] args) {

//1727 => 1727.00
//1727.1 => 1727.10
//1727.23 => 1727.23
//1727.236 => 1727.23
//1727.231 => 1727.23

double money = 1727.1;

System.out.println(new BigDecimal(money).setScale(2, BigDecimal.ROUND_UNNECESSARY));
}
}

Exception in thread "main" java.lang.ArithmeticException: Rounding necessary


please advise
adam
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 35253
    
    7
It's ROUND_DOWN you want in this case.

For formatting you can use the DecimalFormat.format method. That class's setMinimumFractionDigits and setMaximumFractionDigits methods control the number of fractional digits.

double money = 1727.1;
...new BigDecimal(money)

Don't use float or double where money is involved. " new BigDecimal("1727.1") " is the proper constructor for this.


Android appsImageJ pluginsJava web charts
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: BigDecimal money format chop off to 2 decimal
 
Similar Threads
BigDecimal divide question
BigDecimal
Unpredicatable rounding decimals using Number Format/ Decimal Format
converting a double value
Generating compound interest with integers