# ArithmeticException problem with BigDecimal (I think)

Page 1 of 1

## 11 Replies - 1578 Views - Last Post: 20 January 2012 - 08:35 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=263582&amp;s=15a58fe00762577533f83c44c43a6baa&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 stevedench2003

Reputation: 1
• Posts: 39
• Joined: 29-December 11

# ArithmeticException problem with BigDecimal (I think)

Posted 20 January 2012 - 04:31 AM

Yes I am a student, But no I am not lazy,
Yes I do want to learn, No I do not want someone to just do the code without explaining why!
I have been learning Java using netbeans 7 for the past month. The course we are doing is very intensive and we only have one 3 hr lesson, once a week, for 2 months. In this time we are expected to complete an introduction to java course that others students cover through an entire year. Already in this month from knowing nothing what soever about any programming language i have already completed 3 projects, 1) phone problem (multiple user questions program) with which I had help from a great helpful person on here. 2)bubblesort array (scanner user input then display) 3) Grade calculator (simple math for working out grade, avarage etc.) With this project the question was as follows

Write a program which allows the user to input the length and the width of a room (in cm). The program must then calculate and display the area of the room.

Now get the program to accept dimensions of floor tiles and the cost per square metre. Calculate the number of tiles that will be needed to fully cover the floor. Calculate the total cost of tiles, vat at 20% and the amount payable. Ensure that your program displays all calculated values.

The application should do the following:
a) After suitable prompts, read in the length and width of a room in centimetres (cm).
Display the area of the room in square metres (m2).
c) After suitable prompts, read in the dimensions of the floor tile in centimetres (cm).
d) After suitable prompts, read in the cost of the floor tiles in pounds per square metre (£/m2).
e) Calculate and display the number of tiles that will be needed to fully cover the floor.
f) Calculate and display:
1. The cost of the tiles before VAT.
2. The amount of VAT (20%) to be paid.
3. The total amount payable.

I managed to get this to work using int's (make them input cm's and pence etc) which is what all the other students have done. This although will create obvious errors is all thats called for (we write a test out for it) but it's just my nature that i can't just hand in something that is flawed.. So i next rewrote the program to use doubles.. of course as you all know (and I quickly learned) there is a big problem with in correct math, After more research i come to find out about bigDecimal (in class we only shown int, double, boolean, char & string) So i started using that.. The problem is that i recieve this message "Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1616)
at FloorTool2.everyThing(FloorTool2.java:128)
at FloorTiling2.main(FloorTiling2.java:21)"

In the code below I have put in bold the line of code this is calling as java:128. Further research has lead me to the conclusion that the erroe is caused my too many decimal point numbers (ie 1 divided by 3) but for some reason i have tried to put .setScale(2, RoundingMode.HALF_UP) everywhere in the line of code to fix the problem but it changes nothing and it won't let me put it on tileCost Could one of you wise people please let me know what it is that i'm doing wrong and can't work out?
Please don't just fix the code.. i need an explanation too so that i can understand why this is so..
Also some of you may notice other problems either later on in the code or even a better way to write this code. If this is the case please explain this in depth please so that i learn.. heres the code
```import java.util.*;

import java.text.*;

import java.math.*;

public class FloorTool2 {

BigDecimal roomLength, roomWidth, roomCm2, roomM2, tileLength, tileWidth, tileCm2, tileM2, tileM2£, vaT, roomM2AndCm;
BigDecimal correctTiles£, correctTilesVat, correctTilesTotal, completeTiles£, completeTilesVat, completeTilesTotal;
BigDecimal tileCost, tileCostRounded, tilesNeeded, tilesNeededRoundedUp, completeTilesVatRounded, correctTiles£Rounded;
BigDecimal correctTilesVatRounded;
BigDecimal vat = new BigDecimal("0.20");
BigDecimal m2Math = new BigDecimal("0.0001");

public void everyThing() {

Scanner sc = new Scanner(System.in);

System.out.println("\\=# Welcome to the Flooring Expert #=//");

Boolean ContinueLoop1 = true;

do {

try {

System.out.println("To start, please enter the length of the Room in CM's (as a whole number without the 'CM' sign)?");
System.out.println("For 187cms (or 1 meter & 87 cm) type in '187' (* * * NOT '1.87' or '187CM' * * *)");
System.out.println("For 100cms (or 1 meter) type in '100' (* * * NOT '1.00' or '1' or '100CM' * * *)");
System.out.println("For 64cms (or 0 meters & 64 cm) type '64' (* * * NOT '0.64', or '64CM' * * *)");

roomLength = new BigDecimal(sc.nextDouble());

System.out.println("Now please enter the width of the Room?");
System.out.println("In the same formal as lentgh please, (Number of Centimeter's) ");

roomWidth = new BigDecimal(sc.nextDouble());

roomCm2 = roomLength.multiply(roomWidth);

roomM2 = roomCm2.multiply(m2Math);

roomM2AndCm = roomM2.setScale(2, RoundingMode.HALF_UP);

ContinueLoop1 = false;
} catch (InputMismatchException e) {

sc.nextLine();

System.out.println("# # Silly Human!! Computers don't make mistakes! Fallible Humans do! Read the 'WHOLE' question carefully # #");
System.out.println("");
System.out.println("Lets start again shall we...");
}

} while (ContinueLoop1);

System.out.println("");
System.out.println("");
System.out.println("Thank you for your input in.....");
System.out.println("The Room you are flooring is " + roomM2AndCm + " m2 (m2 = Meters Squared/Rounded up to the nearest 2 decimal point)");
System.out.println("");
System.out.println("");

Boolean ContinueLoop2 = true;

do {

try {

System.out.println("Now please enter the length of the Tiles, that you are using (also) in CM's?");
System.out.println("* * * in the same whole number format as used earlier* * *");

tileLength = new BigDecimal(sc.nextDouble());

System.out.println("And what is the width of the Tiles (again) in CM's?");

tileWidth = new BigDecimal(sc.nextDouble());

tileCm2 = tileLength.multiply(tileWidth);

tileM2 = tileCm2.multiply(m2Math);

System.out.println("");
System.out.println("How much do the Tiles cost £/m2? (Pounds per square meter");
System.out.println("Please do not use a '£' sign, and just use ONLY a whole, 1 point or 2 point decimal number!");
System.out.println("for £1.67 per square meter type '1.67' (* * * NOT '167' or '0.167' * * *)");
System.out.println("for 85p type '0.85' (* * * NOT '85p' or '£0.85 or '85' or 0.085 * * *)");
System.out.println("for £17 type '17.00' or '17' (* * *NOT '£17' or '0.17'  * * *)");

tileM2£ = new BigDecimal(sc.nextDouble());

tileCost = tileM2£.divide(tileM2);   //---Error is here

tileCostRounded = tileCost.setScale(2, RoundingMode.HALF_UP);

ContinueLoop2 = false;
} catch (InputMismatchException e) {

sc.nextLine();

System.out.println("# # Silly Human!! Computers don't make mistakes! Fallible Humans do! Read the 'WHOLE' question carefully # #");
System.out.println("");
System.out.println("Thought we'd envolved from that by now!.. Lets try again shall we...");
System.out.println("");
System.out.println("");
}

}while(ContinueLoop2);

tilesNeeded = roomM2.multiply(tileM2);

tilesNeededRoundedUp = tilesNeeded.setScale(2, RoundingMode.CEILING);

System.out.println("# # Thank you for using the Flooring Expert # #");
System.out.println("");

correctTiles£ = tileM2£.multiply(roomM2);

correctTiles£Rounded = correctTiles£.setScale(2, RoundingMode.HALF_UP);

correctTilesVat = correctTiles£Rounded.multiply(vat);

correctTilesVatRounded = correctTilesVat.setScale(2, RoundingMode.CEILING);

completeTiles£ = tileCostRounded.multiply(tilesNeededRoundedUp);

completeTilesVat = completeTiles£.multiply(vat);

completeTilesVatRounded = completeTilesVat.setScale(2, RoundingMode.CEILING);

System.out.println("This totals as £"+correctTiles£Rounded+" (for "+tilesNeeded+" Tiles) With a total VAT of £"+correctTilesVatRounded+" to be paid.....For a grand total of £"+correctTilesTotal);
System.out.println("Or as £"+completeTiles£+" (x "+tilesNeededRoundedUp+" Complete Tiles) With a total VAT of £"+completeTilesVatRounded+" to be paid.....For a grand total of £"+correctTilesTotal);
}

}
```

This post has been edited by smohd: 20 January 2012 - 07:29 AM
Reason for edit:: code tags fixed

Is This A Good Question/Topic? 0

## Replies To: ArithmeticException problem with BigDecimal (I think)

### #2 pbl

• There is nothing you can't do with a JTable

Reputation: 8378
• Posts: 31,956
• Joined: 06-March 08

## Re: ArithmeticException problem with BigDecimal (I think)

Posted 20 January 2012 - 04:57 AM

After 16 posts you should know it

### #3 stevedench2003

Reputation: 1
• Posts: 39
• Joined: 29-December 11

## Re: ArithmeticException problem with BigDecimal (I think)

Posted 20 January 2012 - 05:04 AM

I thought it was just my browser, my mistake i had double code tags at the beginning and at the end instead of just once and the code in between them, Also the edit box won't appear now so won't let me edit the original post
```import java.util.*;

import java.text.*;

import java.math.*;

public class FloorTool2 {

BigDecimal roomLength, roomWidth, roomCm2, roomM2, tileLength, tileWidth, tileCm2, tileM2, tileM2£, vaT, roomM2AndCm;
BigDecimal correctTiles£, correctTilesVat, correctTilesTotal, completeTiles£, completeTilesVat, completeTilesTotal;
BigDecimal tileCost, tileCostRounded, tilesNeeded, tilesNeededRoundedUp, completeTilesVatRounded, correctTiles£Rounded;
BigDecimal correctTilesVatRounded;
BigDecimal vat = new BigDecimal("0.20");
BigDecimal m2Math = new BigDecimal("0.0001");

public void everyThing() {

Scanner sc = new Scanner(System.in);

System.out.println("\\=# Welcome to the Flooring Expert #=//");

Boolean ContinueLoop1 = true;

do {

try {

System.out.println("To start, please enter the length of the Room in CM's (as a whole number without the 'CM' sign)?");
System.out.println("For 187cms (or 1 meter & 87 cm) type in '187' (* * * NOT '1.87' or '187CM' * * *)");
System.out.println("For 100cms (or 1 meter) type in '100' (* * * NOT '1.00' or '1' or '100CM' * * *)");
System.out.println("For 64cms (or 0 meters & 64 cm) type '64' (* * * NOT '0.64', or '64CM' * * *)");

roomLength = new BigDecimal(sc.nextDouble());

System.out.println("Now please enter the width of the Room?");
System.out.println("In the same formal as lentgh please, (Number of Centimeter's) ");

roomWidth = new BigDecimal(sc.nextDouble());

roomCm2 = roomLength.multiply(roomWidth);

roomM2 = roomCm2.multiply(m2Math);

roomM2AndCm = roomM2.setScale(2, RoundingMode.HALF_UP);

ContinueLoop1 = false;
} catch (InputMismatchException e) {

sc.nextLine();

System.out.println("# # Silly Human!! Computers don't make mistakes! Fallible Humans do! Read the 'WHOLE' question carefully # #");
System.out.println("");
System.out.println("Lets start again shall we...");
}

} while (ContinueLoop1);

System.out.println("");
System.out.println("");
System.out.println("Thank you for your input in.....");
System.out.println("The Room you are flooring is " + roomM2AndCm + " m2 (m2 = Meters Squared/Rounded up to the nearest 2 decimal point)");
System.out.println("");
System.out.println("");

Boolean ContinueLoop2 = true;

do {

try {

System.out.println("Now please enter the length of the Tiles, that you are using (also) in CM's?");
System.out.println("* * * in the same whole number format as used earlier* * *");

tileLength = new BigDecimal(sc.nextDouble());

System.out.println("And what is the width of the Tiles (again) in CM's?");

tileWidth = new BigDecimal(sc.nextDouble());

tileCm2 = tileLength.multiply(tileWidth);

tileM2 = tileCm2.multiply(m2Math);

System.out.println("");
System.out.println("How much do the Tiles cost £/m2? (Pounds per square meter");
System.out.println("Please do not use a '£' sign, and just use ONLY a whole, 1 point or 2 point decimal number!");
System.out.println("for £1.67 per square meter type '1.67' (* * * NOT '167' or '0.167' * * *)");
System.out.println("for 85p type '0.85' (* * * NOT '85p' or '£0.85 or '85' or 0.085 * * *)");
System.out.println("for £17 type '17.00' or '17' (* * *NOT '£17' or '0.17'  * * *)");

tileM2£ = new BigDecimal(sc.nextDouble());

tileCost = tileM2£.divide(tileM2);

tileCostRounded = tileCost.setScale(2, RoundingMode.HALF_UP);

ContinueLoop2 = false;
} catch (InputMismatchException e) {

sc.nextLine();

System.out.println("# # Silly Human!! Computers don't make mistakes! Fallible Humans do! Read the 'WHOLE' question carefully # #");
System.out.println("");
System.out.println("Thought we'd envolved from that by now!.. Lets try again shall we...");
System.out.println("");
System.out.println("");
}

}while(ContinueLoop2);

tilesNeeded = roomM2.multiply(tileM2);

tilesNeededRoundedUp = tilesNeeded.setScale(2, RoundingMode.CEILING);

System.out.println("# # Thank you for using the Flooring Expert # #");
System.out.println("");

correctTiles£ = tileM2£.multiply(roomM2);

correctTiles£Rounded = correctTiles£.setScale(2, RoundingMode.HALF_UP);

correctTilesVat = correctTiles£Rounded.multiply(vat);

correctTilesVatRounded = correctTilesVat.setScale(2, RoundingMode.CEILING);

completeTiles£ = tileCostRounded.multiply(tilesNeededRoundedUp);

completeTilesVat = completeTiles£.multiply(vat);

completeTilesVatRounded = completeTilesVat.setScale(2, RoundingMode.CEILING);

System.out.println("This totals as £"+correctTiles£Rounded+" (for "+tilesNeeded+" Tiles) With a total VAT of £"+correctTilesVatRounded+" to be paid.....For a grand total of £"+correctTilesTotal);
System.out.println("Or as £"+completeTiles£+" (x "+tilesNeededRoundedUp+" Complete Tiles) With a total VAT of £"+completeTilesVatRounded+" to be paid.....For a grand total of £"+correctTilesTotal);
}

}

```

### #4 stevedench2003

Reputation: 1
• Posts: 39
• Joined: 29-December 11

## Re: ArithmeticException problem with BigDecimal (I think)

Posted 20 January 2012 - 06:14 AM

So this is a complicated problem (53 views no answer)? I thought it was just a very simple problem with line 091 (in the above example) with just a simple solution that had not been covered in my 5 lessons of java...

This post has been edited by stevedench2003: 20 January 2012 - 06:15 AM

### #5 cfoley

• Cabbage

Reputation: 2388
• Posts: 5,012
• Joined: 11-December 07

## Re: ArithmeticException problem with BigDecimal (I think)

Posted 20 January 2012 - 06:56 AM

I looked at it earlier and immediately closed the tab. Your description of the problem, a copy-pasted, long-winded question and 140 lines of untagged code is a wall of text I simply don't have time for in the middle of the working day.

The exception tells you the number you are trying to create is irrational (i.e. has infinite decimal digits) like pi or 10/3. You need to specify the precision you are looking for. I can't remember if this is done in the multiply/divide method or in the constructor but now you have somewhere to start looking.

If you need more help, please put together a short demo (about 5-10 lines) that captures your problem.

### #6 stevedench2003

Reputation: 1
• Posts: 39
• Joined: 29-December 11

## Re: ArithmeticException problem with BigDecimal (I think)

Posted 20 January 2012 - 07:10 AM

74 Views and no answer... Well I must be some sort of genius as I have managed to solve this by myself after just 5 lessons of java programming, in which i'd had no experience in what-so-ever..

For those that may come across similar problems the solution is as follows

on line 093 tileCost = tileM2£.divide(tileM2);

instead of changing anything (tileM2£/tileM2) to on too .setScale(2, RoundingMode.HALF_UP you simple just change the line of code to tileCost = tileM2£.divide(tileM2, 2, RoundingMode.HALF_UP);
So no setScale.....

Now that I have solved this by myself.. undoubtedly the 74 people who viewed this problem will all give their 2 penny's worth making comments to say blah blah blah etc. all claiming to know how to have solved this, and with really creative and inventive reasons as to why they never commented before. (ie it was simple & best you worked it out yourself, or your post was written out wrong/confusing etc etc etc.) But I will say to all you java newbie's like me to take heart.. these guys really didn't have a clue.. and i'm really am no genius (not in java anyway) So no matter whatever creative messages they write... This just goes to show that anyone i mean anyone can in fact get their head around something
that the supposed experts can't and vice-versa... So if you get stuck in java.. Don't give up even if noone is able to help you..

### #7 cfoley

• Cabbage

Reputation: 2388
• Posts: 5,012
• Joined: 11-December 07

## Re: ArithmeticException problem with BigDecimal (I think)

Posted 20 January 2012 - 07:21 AM

I replied with an answer, probably while you were typing your rant, which explains that you need to set a precision.

Well done for working it out yourself though.

My reason for not helping out earlier is simple and explained above.

### #8 stevedench2003

Reputation: 1
• Posts: 39
• Joined: 29-December 11

## Re: ArithmeticException problem with BigDecimal (I think)

Posted 20 January 2012 - 07:27 AM

cfoley, on 20 January 2012 - 07:21 AM, said:

I replied with an answer, probably while you were typing your rant, which explains that you need to set a precision.

Well done for working it out yourself though.

My reason for not helping out earlier is simple and explained above.

Yes thank you, it must of been while ranting. Although in the 'long winded' question I did in fact explain I knew why the problem was being caused Qoute from original post Further research has lead me to the conclusion that the erroe is caused my too many decimal point numbers (ie 1 divided by 3) but for some reason i have tried to put .setScale(2, RoundingMode.HALF_UP) everywhere in the line of code to fix the problem but it changes nothing and it won't let me put it on tileCost Could one of you wise people please let me know what it is that i'm doing wrong and can't work out? I just needed the answer as to how to solve it.. Thanks anyway and i've marked you as the most helpfull.. thanks again..

### #9 cfoley

• Cabbage

Reputation: 2388
• Posts: 5,012
• Joined: 11-December 07

## Re: ArithmeticException problem with BigDecimal (I think)

Posted 20 January 2012 - 07:37 AM

Thanks for the up votes. Remember that the number of views includes your own, about 5 or 6 of mine (at this point), anonymous users who don't have an account here (who can't post), and possibly spiders, page scrapers, etc.

Of the rest, its likely most of them didn't read your post. It's just too long. For a simple problem like this that you have already narrowed down so well, it's best to throw together a 5-10 line demo that encapsulates the problem. Include the exception detail (like you did) and add a short paragraph explaining the problem. You'll find people are much happier to help out then.

Hope you have better luck next time you ask for help here.

### #10 stevedench2003

Reputation: 1
• Posts: 39
• Joined: 29-December 11

## Re: ArithmeticException problem with BigDecimal (I think)

Posted 20 January 2012 - 08:01 AM

cfoley, on 20 January 2012 - 07:37 AM, said:

Thanks for the up votes. Remember that the number of views includes your own, about 5 or 6 of mine (at this point), anonymous users who don't have an account here (who can't post), and possibly spiders, page scrapers, etc.

Of the rest, its likely most of them didn't read your post. It's just too long. For a simple problem like this that you have already narrowed down so well, it's best to throw together a 5-10 line demo that encapsulates the problem. Include the exception detail (like you did) and add a short paragraph explaining the problem. You'll find people are much happier to help out then.

Hope you have better luck next time you ask for help here.

Ok thanks for the advise. I did originally think to do that (would of been far quicker on my behalf) but thought i better to give the whole (long-winded) picture as there may of been a problem elsewhere.. or another one that would of happened next.. But i'll follow your advise in future..

Amazing site by the way. with amazing help.. with my other (first) post, people were answering and helping me in minutes.. nearly the whole day... like a said.. a great site with amazingly helpful people :-)

### #11 cfoley

• Cabbage

Reputation: 2388
• Posts: 5,012
• Joined: 11-December 07

## Re: ArithmeticException problem with BigDecimal (I think)

Posted 20 January 2012 - 08:11 AM

No problem. It can be difficult to know whether to post the whole program or just a few lines, especially when it's something you need help understanding.

However, if you can replicate a problem in a small piece of code it gives us something to paste into our IDE. We can make modifications and test them with minimal effort.

Then if you are having trouble incorporating our solutions into your main program, that's often the time to post the whole code.

### #12 Dogstopper

Reputation: 2965
• Posts: 11,222
• Joined: 15-July 08

## Re: ArithmeticException problem with BigDecimal (I think)

Posted 20 January 2012 - 08:35 AM

It IS a fine line between too much and too little. Like cfoley said, a demo of what's going on is a good idea and then posting the error(s). If we need more context at that point, we will ask for it.