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);
Related
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.
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'm writing a convertor by Eclipse and my results are with 9 or 10 decimal digits and I want to make it 2 or 3.
This is part of my code:
double gr = 0;
if (edtGr.getText().toString().length() > 0) {
gr = Float.parseFloat(edtGr.getText().toString());
}
if (edtNgr.getText().toString().length() > 0) {
gr = (Double.parseDouble(edtNgr.getText().toString())) / 1000000000;
}
edtNgr.setText("" + (gr * 1000000000));
edtGr.setText("" + gr);
This code converts grams to nanograms and I want the result in 2 or 3 decimal digits.
Try
String.format("%.2f", gr * 1000000000);
For 3 decimal places,
String.format("%.3f", gr * 1000000000);
For 2 Decimal places change your code as
edtNgr.setText(""+ ((String.format("%.2f", (gr * 1000000000)))));
edtGr.setText("" + ((String.format("%.2f", gr))));
And for 3 Decimal points
edtNgr.setText("" + ((String.format("%.3f", (gr * 1000000000)))));
edtGr.setText("" + ((String.format("%.3f", gr))));
Also You can use DecimalFormat. One way for (using 3 points) to use it:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(3);
edtNgr.setText("" + df.format(gr * 1000000000));
edtGr.setText("" +df.format(gr));
Please see more at How to format Decimal Number in Java
You can use
double roundOff = Math.round(yourDouble * 1000.0) / 1000.0;
Another way
BigDecimal doubleVal = new BigDecimal("123.13698");
BigDecimal roundOff = doubleVal.setScale(2, BigDecimal.ROUND_HALF_EVEN);
You can use NumberFormatter like
NumberFormat formatter = NumberFormat.getInstance();
formatter.setMaximumFractionDigits(3);
then format it like
formatter.format(36.55468865)
This will give the output 36.555 rounding off 55468865 to 555
(double)Math.round(value * 100000) / 100000.. the number of precision indicated by the number of zeros.
Or
double d = 12345.2145;
BigDecimal bd = new BigDecimal(d).setScale(3, RoundingMode.HALF_EVEN);
d = bd.doubleValue();
Change the 1st argument in setScale method as per the precision required.
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;
I have a double variable test. I want to extract the all digits before decimal point and two digits after the decimal point store the output in integer variables dollar, cents. how can i do it? I dont want any rounding to happen.
example:
double test= 12.1234
Output
int dollar =12;
int cents =12;
double test =1235.0
output
int dollar=1235
int cents =0
For currency, especially when you don't want any rounding, you should use the BigDecimal class. Something like:
BigDecimal test = new BigDecimal("12.1234");
int dollar = test.intValue();
int cents = test.scaleByPowerOfTen(2).intValue() - dollar * 100;
You can do:
double test= 12.1234;
int dollar = (int) test;
int cents = (int) ((test-dollar) * 100);
How about:
dollar = test;
test -= dollar;
cents = test * 100;
Line 1 assigns the integer part of test (12) to the integer 'dollar.'
Line 2 removes the 12 dollars from the test value.
Line 3 assigns 100 times the fractional part of test to cents. Note that I don't round here. For that, you'd have to:
cents = (test + 0.005) * 100
How about something like this. Rather than printing the values, you can simply assign them as you see fit.
double d = 32.456;
System.out.println( (int)d );
System.out.println( d-(int)d);
String[] s = Double.toString(test).split(".");
String dol = s[0];
String cent = s[1].substring(0,1);
For double values greater than 10^13, there won't be ANY significant digits after the notional decimal point.
You should not be using double or float for representing financial quantities. Use int or long (appropriately scaled and with explicit checks for overflow) or BigDecimal.