Displaying BigDecimal as Integer while Keeping Original Value - java

The purpose of this program is to give correct change. For Example:
Input: $45.54
Output: 4 Ten Dollar Bills,
1 Five Dollar Bills,
2 Quarters,
4 Pennies.
Now onto my question:
I want to display a BigDecimal as an integer without losing the original value, as I have to continue my division all the way down until i get to 0.01 for pennies.
My Current Code looks like:
BigDecimal tenDollar = BigDecimal.valueOf(10);
BigDecimal tenDollarNext;
BigDecimal fiveDollar = BigDecimal.valueOf(5);
BigDecimal fiveDollarNext;
/* Get Input From User */
System.out.print("Please enter the amount to be converted: ");
Scanner scan = new Scanner(System.in);
BigDecimal money = scan.nextBigDecimal();
NumberFormat usdFormat = NumberFormat.getCurrencyInstance(Locale.US);
usdFormat.setMinimumFractionDigits(2);
usdFormat.setMaximumFractionDigits(2);
System.out.println("Amount you entered: " + usdFormat.format(money));
/* Begin Processing and Displaying Information */
tenDollarNext = money.divide(tenDollar);
System.out.println(tenDollarNext + " Ten Dollar Bills");
fiveDollarNext = tenDollarNext.divide(fiveDollar, 0, RoundingMode.FLOOR);
System.out.println(fiveDollarNext + " Five Dollar Bills");
Which ends up Displaying:
Please enter the amount to be converted: 45.54
Amount you entered: $45.54
4.554 Ten Dollar Bills
0 Five Dollar Bills
My goal is to have the 4.554 be displayed as 4 without losing the decimal places at the end for the calculation. I'm sure there is a simple answer to this, I was hoping someone could either tell me the conversion for it or point me in the direction of where I could find the answer. None of my search queries have been helpful.

Use the divideToIntegralValue method of the BigDecimal class, in place of divide. This returns a BigDecimal whose value is an integer. You can then subtract the appropriate amount from money and continue on.

Related

Looking to get the yearly returns on this total compound interest calculator

I'm really new to Java so please excuse if this isn't the 100% right way to even write this code.
So I've been messing around with this code for about 6 hours now, and I can not for the life of me figure out how to fix this issue:
I have a compound interest calculator that takes user input for the variables of term length, initial amount, and APR. I can get the answer I want if it was just the simple one time calculation, but I really want it to show me the amount increased each year of a term. For example:
If the interest is calculated for 10 years, I want it to show me the amount for each year leading up to it. Right now all I get is a static number of 1, or infinity.
How do I get this program to show me the total amount for the term (i.e. the length of the user input investment), broken down per year with the amount shown per year?
The code is:
import java.util.Scanner;
import java.lang.Math;
public class CompoundInterestCalculator {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
double initial; // the intial amount your loan is set for
int term; // the number of years you want to calculate
float yearlyrate; // interest rate
int repeat;
// System message to alert users to program use
System.out.printf("Hi there! I can calculate compound interest for you at a fixed interest
rate and term.\n\nPlease enter numbers without commas or symbols to get an accurate result!");
// Prompt for initial investment amount
System.out.println("\nPlease enter your initial investment.");
// Store value of user input for initial investment
initial = scan.nextDouble();
// Prompt for interest percentage
System.out.println();
System.out.println("Please enter the annual interest percentage.");
System.out.println();
// Store value of user input for interest amount
yearlyrate = scan.nextFloat();
// Prompt for length of the term for investment
System.out.println();
System.out.println("Please enter the length of your investment in years.");
// Store Value of user input for term length
term = scan.nextInt();
//For loop to set up calulations, repeats, and totals
for(repeat = 0; repeat < term; repeat++) {
System.out.println();
System.out.println("Your investment amount after" + (repeat+1) + "years is:");
// calculation for determining compound interest at a yearly rate and over the term
double total = Math.pow(initial * (1 + (yearlyrate/100) / 12) , 12/term);
// Displays the total value to the user
System.out.println("$" + total);
// Seperation line to clean it up
System.out.println();
// Close the scanner
scan.close();
}
}
}
Any help would be greatly appreciated because I am really out of my depth with this one.
Just a small change in your calculation logic:
// calculation for determining compound interest at a yearly rate and over the term
double total = initial * Math.pow((1 + (yearlyrate/100)) , (repeat+1));

How do I loop until I get the right answer?

I'm trying to program something that repeats itself until it gets the amount right. My program is basically a loan program that helps you figure out how long it'll take for you to pay off a loan with interest. So far, I managed to get the first month to print out (although not exactly right...), but I need it to keep repeating until the loan amount has been paid off. I hope that makes sense.
import java.util.*;
import java.io.*;
public class Project4{
static Scanner console = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException
{
Scanner keyboard = new Scanner(System.in);
Scanner user_input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
PrintWriter outFile = new PrintWriter("Project4.out");
double lamnt;
double mpay;
double intrestrate;
double mnthintrest;
double mintrestrate;
System.out.print("Enter the Loan Amount: ");
lamnt = keyboard.nextDouble();
System.out.println();;
System.out.print("Enter the intrest rate (Ex:5.75): ");
intrestrate = keyboard.nextDouble();
System.out.println();
System.out.print("Enter the monthly payment you want to make: ");
mpay = keyboard.nextDouble();
System.out.println();
mintrestrate = intrestrate/12;
mnthintrest = lamnt*mintrestrate;
System.out.println("The first month intrest rate is:" + pay);
}
}
I was suggested using a while loop but I'm not too sure how to make the while loop keep going until the loan amount is paid off. Also yes I know the outcome isn't right, I'm working on that part. I'm not too sure how to space out the titles properly.
I need the output to look like this: (using 1000 in loan payment, 7.2 in interest rate, 25 for monthly pay)
Amount loan after payment #1 is: 981.00 Principle is: 19.00 Interest is: 6.00
Amount loan after payment #2 is: 961.89 Principle is: 19.11 Interest is: 5.89
So, if you want to use a while loop until your loan is paid off, just do something like:
while (lamnt > 0) {
// Do stuff to pay off the loan here.
}
As long as you're updating the lamnt within the loop, that should work.
Hope that helped!
;)
Edit: Also, make sure you're only creating scanners that you actually use. And don't forget to close them at the end of the scope!
Assuming that interest rate would be entered in percentage, the mnthintrest calculation would need an additional multiplication by 1/100 i.e. 0.01
mnthintrest = lamnt*mintrestrate*(0.01);
You also need to edit the variable pay to mpay
System.out.println("The first month intrest rate is:" + pay);
I think your logic for money paid per month should be ( as others suggested) - reducing the loan amount until it reaches zero.
Now coming to implementation, you will be reducing the amount and since we wouldn't want the original data ( variable) to be affected, we could first store it an temporary variable.
For keeping track of #number of payment, we can keep the month count in another variable.
You could think of something like this:
double temp = lamnt;
int monthNumber = 1;
while(temp>0){
mnthintrest = temp*mintrestrate*0.01;
double principlePaidPerMonth= mpay- mnthintrest;
temp = temp - principlePaidPerMonth; // reducing the principle amount paid before printing
System.out.println("\nAmount left after payment "+monthNumber+" is:" + temp);
System.out.println("This month intrest is:" + mnthintrest);
System.out.println("Principle paid is:" + principlePaidPerMonth);
monthNumber++;
}
// text to be printed could be different
It is a good practice to keep variable names as meaningful as possible and to declare the variables as much closer to their first use.
So you could declare the variables for interest and interest rate just at the time of initializing above where the while loop part starts.
double mintrestrate = intrestrate/12;
double mnthintrest = lamnt*mintrestrate;
For formatting, you could use System.out.printf() instead of println - this could help format the number of digits shown after decimal
For getting precision - you could use absolute/ceiling functions available in Math class.

Why is the last line of my code not printing? Also, what's the simplest way for me to round numbers to 2 decimals? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 6 years ago.
When running my program, the last line displaying yearly gas expense is not showing... what have I done wrong? Also would like some help rounding figures to 2 decimal points...
I tried implementing a few strategies but none of them worked.
Any help is appreciated!
public class GasExpenses {
public static void main(String[] args) {
//Use scanner in order to retrieve user input.
Scanner keyboard= new Scanner(System.in);
//Declare variables.
int milesPerWeek;
double milesPerGallon,costOfGas;
System.out.println("GAS EXPENSES");
//Get user input.
System.out.println("How many miles do you drive a week?");
milesPerWeek = keyboard.nextInt();
//Get user input.
System.out.println("How many miles per gallon does your auto get?");
milesPerGallon=keyboard.nextDouble();
//Get user input.
System.out.println("What is the current cost of gas?");
costOfGas=keyboard.nextDouble();
//Calculate miles per year.
int milesPerYear=(milesPerWeek*52);
//Display calculated yearly mileage.
System.out.println("At " + milesPerWeek + "miles per week, you travel "+
milesPerYear + " miles per year.");
//Calculate and display calculated weekly & yearly gallons of gas used.
double gallonsPerWeek=(milesPerWeek/milesPerGallon);
System.out.println("Gallons per week:" + gallonsPerWeek);
double gallonsPerYear=(gallonsPerWeek*52);
System.out.println("Gallons per year:" + gallonsPerYear);
//Calculate and display calculated weekly & yearly gas expense.
System.out.println("With gas at $" +costOfGas + " per gallon, you will
spend: ");
double weeklyGasExpense=(costOfGas*milesPerWeek);
System.out.println("Gas expense per week: $" +weeklyGasExpense);
double yearlyGasExpense=(costOfGas*milesPerYear);
System.out.println("Gas expense per year: $" +yearlyGasExpense);
//Calculate and display calculated weekly & yearly gas expense based on
increased gas price.
double costIncrease= (costOfGas+1);
System.out.println("If gas goes up by one dollar per gallon to $" +
costIncrease +(" per gallon, you will spend:"));
double weeklyIncreasedGas=(costIncrease*milesPerWeek);
double yearlyIncreasedGas=(costIncrease*milesPerYear);
System.out.println("Gas expense per week : $" +weeklyIncreasedGas);
System.out.print("Gas expense per year : $" +yearlyIncreasedGas);
}}
Run system.out.flush() at the end of your code to make sure everything is printed.
For the rounding you could try this answer round up to 2 decimal places in java?
For first question, this line works for me given your code:
System.out.print("Gas expense per year : $" +yearlyIncreasedGas);
For second do this:
double number = 111.12345;
double result = Math.round(number * 100.0) / 100.0;

Preserving Accuracy When Formatting a Floating Point Number to Display With Two-point Precison (Java)

Here's the program. It's meant to calculate an employee's net pay based on hours worked, hourly rate, tax withholds, etc. It calculates correctly, but the double-point precision formatting rounds the last decimal, losing the calculation's accuracy.
Sample Input:
Name: Smith
Hours worked this week: 10
Hourly rate: 6.75
Federal tax withhold: 20%
State tax withold: 9%
Output:
Summary
Employee: Smith
Gross Pay: 67.50
Federal Withholding: 13.50
State Withholding: 6.08
Total Deduction: 19.58
Net Pay: 47.93
import java.util.*;
public class Payroll
{
static Scanner key = new Scanner(System.in);
public Payroll()
{
System.out.print("Name: ");
String name = key.next();
System.out.print("Hours worked this week: ");
int hoursWorked = key.nextInt();
System.out.print("Hourly rate: ");
double payRate = key.nextDouble();
double payPreTax = hoursWorked * payRate;
System.out.print("Federal tax withhold: ");
String fedTaxStr = key.next().replace("%", "");
double fedTax = ((Double.parseDouble(fedTaxStr)) / 100) * payPreTax;
System.out.print("State tax withold: ");
String stateTaxStr = key.next().replace("%", "");
double stateTax = ((Double.parseDouble(stateTaxStr)) / 100) * payPreTax;
double amountWithheld = fedTax + stateTax;
double payPostTax = payPreTax - amountWithheld;
System.out.printf("\nSummary\n\nEmployee: " + name + "\nGross Pay: %.2f\nFederal Withholding: %.2f\nState Withholding: %.2f\nTotal Deduction: %.2f\nNet Pay: %.2f", payPreTax, fedTax, stateTax, amountWithheld, payPostTax);
}
public static void main(String[] args)
{
new Payroll();
}
}
Please have mercy; I'm first-year.
Preserving Accuracy When Formatting a Floating Point Number to Display With Two-point Precision
What you are asking for is self-contradictory / impossible.
You say:
It calculates correctly, but the double-point precision formatting rounds the last decimal, losing the calculation's accuracy.
That is correct. The floating point calculation will probably be accurate to at least 10 decimal points. As you note, the loss of accuracy (rounding) is actually happening when you format the number using %.2f in the printf call.
To put it simply, you cannot "preserve accuracy" and also print out the number with only 2 decimal points of precision.
The simple solution is to print with more digits after the decimal place; i.e. use a different format specifier for the number. (For instance ... %.4f would give you 4 digits after the decimal point!)
I recommend that you read the javadocs for Formatter which explains what format specifiers mean.
Actually, there is a second way of looking at this. You are using double for your calculations here. A double is a binary (base-2) floating point representation. Many decimal numbers cannot be represented precisely in binary floating point. (For the same reason that 1 / 3 is not precisely representable in decimal floating point.)
The normal way to deal with this in accounting software is to represent monetary values as integers (e.g. an integer number of cents) or a decimal floating-point representation. In Java BigDecimal is the standard way to represent decimal floating point. It can cope with arbitrary precision.

Why in this Java program the Doubles in a String Output have too many decimals?

In a solution to an exercise in the Book Art and Science of Java I had to write a program that converts Kilograms into the corresponding values in Pounds and Ounces.
I wrote the program but when I try to convert say 1kg, the result the program gives me is:
1 kg = 2 pounds and 3.200000000000006 ounces
Now my constants are 2.2 pounds per kg and 16 ounces per pound so 3.2 ounces is correct. But not with so many 0's and that 6 at the end freaks me out.
Anyone know why this happens and how it can be solved? Thank you!
Here's the code:
/*
* File: KgsLibras.java
* Program that converts kilograms in pounds and ounces.
*/
import acm.program.*;
public class KgsLibras extends ConsoleProgram {
public void run () {
println ("This program will convert kilograms in pounds and ounces");
double kgs = readDouble ("Insert kgs value: ");
double libras = kgs * LIBRAS_POR_KG;
double oncas = (libras - (int)libras) * ONCAS_POR_LIBRA;
println ((int)libras + " libras" + " e " + oncas + " Onças.");
}
private static final double LIBRAS_POR_KG = 2.2;
private static final int ONCAS_POR_LIBRA = 16;
}
That's just a consequence of how floating point works - literally thousands of other references to these issues here on SO alone. The short version is that not all numbers can be represented exactly using floating point numbers, which leads to oddities like the one you're seeing. This document should teach you all you should know about floating point.
In the mean time you can use format to get printf-like formatting options:
System.out.format ("%.0f libras e %.2f Onças.\n",libras,oncas);
or if you have to use that specific println method, use String's format:
println(String.format ("%.0f libras e %.2f Onças.",libras,oncas) );
You can do something like this:
String libras = String.format("$%.2f", VALUE); //For example..
Then, printing libras will suits your needs.
Regarding of your question about Why your program prints it that way, #fvu was faster than me :)

Categories

Resources