I'm trying to write a program that converts kilograms to pounds and ounces. If the user enters 100 kilograms the result I'm expecting is 220 pounds and 7.4 ounces.
I get the correct pound value but my problem is getting the correct ounces value. I don't know what I'm missing. Also when I calculate the ounces value, how do i specify to the program that I only want the answer to the hundredth degree. For example I only want 7.4 ounces and not 7.4353?
import acm.program.*;
public class KilogramsToPoundsAndOunces extends ConsoleProgram {
public void run() {
println("This program converts Kilograms into Pounds and Ounces.");
int kilo = readInt("please enter a number in kilograms: ");
double lbs = kilo * POUNDS_PER_KILOGRAM;
double oz = lbs * OUNCES_PER_POUND;
double endPounds = (int) oz / OUNCES_PER_POUND;
double endOunces = oz - (endPounds * OUNCES_PER_POUND);
println( endPounds + " lbs " + endOunces + "ozs");
}
private static final double POUNDS_PER_KILOGRAM = 2.2;
private static final int OUNCES_PER_POUND = 16;
}
The easiest way would be to use System.out.printf and format the output there:
System.out.printf("%d lbs %.1f ozs", endPounds, endOunces);
If you can't use System.out.printf, you can still use String#format to format the output:
println(String.format("%d lbs %.1f ozs", endPounds, endOunces));
Cases where you need exact decimal value; its better to use BigDecimal data type instead of double.
The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. link
BigDecimal provides methods to round the number to given value.
Use DecimalFormat to print the decimal places in desired format e.g.
DecimalFormat dFormat = new DecimalFormat("#.0");
System.out.println( endPounds + " lbs " + dFormat.format(endOunces) + " ozs");
If you want rounding done upto one decimal place, then multiply the number by 10, round, then divide again and print as below:
double roundedOunces = Math.round(endOunces*10)/10.0;
DecimalFormat dFormat = new DecimalFormat("#.0");
System.out.println( endPounds + " lbs " + dFormat.format(roundedOunces) + " ozs");
EDIT:
Try this for rounding:
double roundedOunces = Math.round(endOunces*10)/10.0;.
Without rounding:
double roundedOunces = endOunces*10/10.0;
Related
I'm trying to figure out a way of converting kilograms (entered by user) to stone and pounds.
For example:
User enters weight as 83.456 kgs, multiply this by 2.204622 to convert to pounds = 184 lbs, divide 184 lbs by 14 to convert to stone = 13.142 stone.
Use the first two digits (13) for stone and separate the remainder to multiply by 14 to get pounds, 0.142 (this is remainder) x 14 = 1.988 lbs, or is there another way to get this result?
Therefore the persons weight is 13 stone and 2 pounds (rounded up or down).
Here's what I have (that works) so far:
pounds = kgs*2.204622;
System.out.printf("Your weight in pounds is: %.0f" , pounds);
System.out.print(" Ibs\n");
stone = pounds / 14
//Can't figure out how to finish the formula in code
I'm assuming that you declared pounds and stone before using them here (i.e. with float pounds; or double pounds; or float pounds = something), or the code wouldn't compile otherwise.
One way to do this is to do it in 2 separate steps, as below:
double kg = 83.456;
double pounds = kg * 2.204622;
double stonesWithDecimal = pounds / 14;
int stone = (int) stonesWithDecimal; // Strip off the decimal
long poundsWithoutStone = Math.round((stonesWithDecimal - stone) * 14); // Take the fractional remainder and multiply by 14
System.out.println("Stone: " + stone + "\nPounds: " + poundsWithoutStone);
Andreas's suggestion is definitely much cleaner, though I wanted to present both since I'm not sure what your familiarity level is with using modulo in programming.
Here's one implementation of that suggestion, though you can do this a few different ways in terms of dealing with the data types (Math.round wants to return a long):
double kg = 83.456;
double pounds = kg * 2.204622;
int stone = (int) pounds / 14;
pounds = (double) Math.round(pounds %= 14);
System.out.println("Stone: " + stone + "\nPounds: " + pounds);
If you are looking for an extensible ready to use library, you can consider Free & open-sourced library UnitOf
It offers 30+ conversion out of the box for Mass.
Example :
double kgFromPound = new UnitOf.Mass().fromPounds(5).toKilograms();
double poundFromKg = new UnitOf.Mass().fromKilograms(5).toPounds();
Hope it helps!
The correct solution rounds early. Here is code as suggested by my initial comment:
double kgs = 83.456;
long pounds = Math.round(kgs*2.204622);
System.out.println("Your weight is " + pounds / 14 + " stone and " + pounds % 14 + " pounds");
Output
Your weight is 13 stone and 2 pounds
If you instead use 69.853 kgs, you get
Your weight is 11 stone and 0 pounds
but this is where thing get dicey if you don't round early.
Both solutions in the (currently accepted) answer by Lightning are wrong, since they round at the wrong time. There is a reason you have to round early.
If you change to use 69.853 kgs in those two solutions, you get
Solution 1:
Stone: 10
Pounds: 14
Solution 2:
Stone: 10
Pounds: 14.0
Both are obviously incorrect, since Pounds should not be 14, aka 1 stone.
The reason for the rounding errors becomes evident if you print the values without rounding
double kgs = 69.853;
double pounds = kgs*2.204622;
System.out.println(pounds + " lbs = " + pounds / 14 + " stone and " + pounds % 14 + " pounds");
Output
153.99946056599998 lbs = 10.999961468999999 stone and 13.999460565999982 pounds
I have a float value of a current weight like e.g. "79.3" kilograms.
I split the float value into a kilogram and a grams value.
I get the right amount of kilograms when parsing the float-value to int.
Then I get the fractional part of the float-value. This fractional part looks like "0,3" which means 0.3 kilograms or 300grams.
In my Programm I can only have 0,100,200,..,900 Grams which would stand for 0-9.
My goal is to remove the "0," so I only get the value of "3".
This is my code for now and I tried some decimal formatting too, but I didn't know how to do it:
public void setCurrentWeightInTheNumberPickers() {
float currentWeightAsFloat = weight_dbHandler.getCurrentWeightFloat();
int currentWeightKilograms = (int) currentWeightAsFloat;
double fractionOfGrams = currentWeightAsFloat % 1;
DecimalFormat df1 = new DecimalFormat("0.##");
String rounded = df1.format(fractionOfGrams);
rounded.replaceFirst("^0+(?!$)", "");
} //public void setCurrentWeightInTheNumberPickers()
Given a string
String gram = "0,3";
you can just do:
gram = gram.substring(gram.lastIndexOf(",") + 1);
which gives the following output when printed
3
Or you can simply do that. No need for strings.
float f = 3.3f;
int g = (int)f;
int h = Math.round((f - g)*10);
and since h is supposed to be grams, you might as well make it *1000
I view this primarily as a math, not a Java, problem. Given a float input in units of kilograms, to obtain only the kilogram component, we can take the floor. To get the grams component, we can multiply by 1000 and then take the mod of 1000.
double input = 79.321;
double kg = Math.floor(input);
System.out.println("kilograms: " + kg);
double g = Math.floor((1000*input) % 1000);
System.out.println("grams: " + g);
kilograms: 79.0
grams: 321.0
Note: I am using double here instead of float, only because Math.floor returns double as its return value.
Okay, I know there is a question quite similar already, but it didn't quite answer my question. Please let me know if I'm doing something wrong though.
I have written a program that gets a temperature in Fahrenheit from the user and converts it to Celcius. It looks like this:
import java.util.Scanner;
public class FahrenheitToCelcius {
public static void main(String[] args) {
double fahrenheit;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a temperature in Fahrenheit: ");
fahrenheit = sc.nextDouble();
double celcius = (fahrenheit - 32) * 5 / 9;
String num = String.format("%.3f", celcius);
System.out.println(" ");
System.out.println(fahrenheit + "F" + " is " + num + "C");
}
}
When it prints the answer out, I want only the first 3 decimal places printed, but not rounded. For example, if the input is 100F, I want 37.777C printed, not 37.778C.
I have tried using DecimalFormat and String.format (like above), but both methods print out 37.778C. Is there a better way to do this?
Thank you for your answers, and I apologise if this is a duplicate.
You can use DecimalFormat, just set the RoundingMode:
DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.FLOOR);
String num = df.format(celcius);
Multiply celsius by 1000 to move the decimal over 3 spots
celsius = celsius * 1000;
Now floor the number and divide by 1000
celsius = Math.floor(celsius) / 1000;
It will remove the need for the String.format() method.
This answer is similar to using Math.floor but probably easier to just cast to int:
Want 2 decimal places? Try this:
System.out.println( (int) (your_double * 100) / 100.0 );
Want 3 decimal places? Try this:
System.out.println( (int) (your_double * 1000) / 1000.0 );
Want 4 decimal places? Try this:
System.out.println( (int) (your_double * 10000) / 10000.0 );
See the pattern? Multiple your double by 10 to the power of the number of decimals you want. After cast, divide by same with decimal zero appended.
You can simply round until 4 decimal places then trim the last character.
String num = String.format("%.4f", celcius);
num = num.substring(0, num.length() - 1);
I have read this question Round a double to 2 decimal places It shows how to round number. What I want is just simple formatting, printing only two decimal places.
What I have and what I tried:
double res = 24.695999999999998;
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(res)); //prints 24.70 and I want 24.69
System.out.println("Total: " + String.format( "%.2f", res )); //prints 24.70
So when I have 24.695999999999998 I want to format it as 24.69
You need to take the floor of the double value first - then format it.
Math.floor(double)
Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.
So use something like:
double v = Math.floor(res * 100) / 100.0;
Other alternatives include using BigDecimal.
public void test() {
double d = 0.29;
System.out.println("d=" + d);
System.out.println("floor(d*100)/100=" + Math.floor(d * 100) / 100);
System.out.println("BigDecimal d=" + BigDecimal.valueOf(d).movePointRight(2).round(MathContext.UNLIMITED).movePointLeft(2));
}
prints
d=0.29
floor(d*100)/100=0.28
BigDecimal d=0.29
Multiply the number by 100 and cast it to an integer. This cuts off all the decimal spaces except the two you want. Divide the result by 100.00. (24.69).
int temp = (int)(res * 100);
double result = temp / 100.00;
or the same thing in one line of code:
double result = ((int)(res * 100)) / 100.00;
In addition to using Math.floor(double) and calculating a scale (e.g. * 100 and then / 100.0 for two decimal points) you could use BigDecimal, then you can invoke setScale(int, int) like
double res = 24.695999999999998;
BigDecimal bd = BigDecimal.valueOf(res);
bd = bd.setScale(2, RoundingMode.DOWN);
System.out.println("Value: " + bd);
Which will also give you (the requested)
Value: 24.69
I am very new. apologies in advance for my coding. I need to print a table that shows year and then a tab over, and then the value with a next line. The value has to be in decimal form.
I have been reading and searching and mixing my code around. I have found it for 1 variable but not for two in same line. I have tried the printf, I have tried the good ol 100 / 100.0 and I either get errors or the decimal never goes to 2 places. I do not need it rounded, just with 2 spaces after. I am obviously going wrong somewhere. I would appreciate any assistance.
import java.util.Scanner;
public class Investment1 {
public static double futureInvestmentValue(double investmentAmount, double monthlyInterestRate, int years){
double principal = 0.0;
double futureInvestmentValue = 0;
for (years = 1; years <=30; years++){
//calculate futureInvestmentValue
futureInvestmentValue = (investmentAmount * (Math.pow (1 + monthlyInterestRate, years * 12)));
System.out.print(years + "\t" + futureInvestmentValue + "\n");
}//end for
return futureInvestmentValue;
}//end futureInvestmentValue
public static void main(String[] args){
Scanner input = new Scanner (System.in);
//obtain Investment amount
System.out.print("Enter Investment amount: ");
double investmentAmount = input.nextDouble();
//obtain monthly interest rate in percentage
System.out.print("Enter annual interest rate in percentage: ");
double annualInterestRate = input.nextDouble();
double monthlyInterestRate = (annualInterestRate / 1200);
int years = 30;
System.out.println("Years\t" + "Future Value");
System.out.print(years + "\t");
System.out.print(years + "\t" + ((int)(futureInvestmentValue(investmentAmount, monthlyInterestRate, years))) + "\n");
}//end main
}//end Investment
You can use system.out.format():
System.out.format("%d \t %.2f", years, futureInvestmentValue);
you should read about format strings, heres a simple usage example:
System.out.println(String.format("%d %.2f",myint,myfloat));
myint will be printed as an integer (even if it's a floating point value) due to the use of the %d in the format string.
myfloat will be printed as a decimal number with 2 digits after the decimal point, thanks to the %f.2 part in the format string.