I want to parse Double value to a specific format. I don't want it as a string.
I am trying
DecimalFormat format3DigitsAfterDecimal = new DecimalFormat("#0.000");
double d = 57;
Double.parseDouble(format3DigitsAfterDecimal.format(d));
This returns 57.0, I want 57.000 returned by format method in double.
Am I possibly asking wrong question ?
A double doesn't have a specific format.
Getting a Double value as 57.0 or 57.000 is the same for the computer but not for the user.
As a human, you don't read Double, but String representation of Double.
If you want a Double to be displayed with 3 decimal, you have to turn it to String using DecimalFormat
double d = 57.0;
NumberFormat numFormat = NumberFormat.getInstance();
numFormat.setMaximumFractionDigits(3);
numFormat.setMinimumFractionDigits(3);
System.out.println(numFormat.format(d));
You can't change the value of a decimal, but you can use NumberFormat to display it with three decimal places by setting minimum and maximum fraction digits like in the example above.
Related
What is the best way to format the following number that is given to me as a String?
String number = "1.574e10" //assume my value will always be a String
I want this to be a String with the value: 1000500000.57
How can I format it as such?
double x = Double.valueOf("1.574e10");
String s = String.format("%.2f", x);
The f specifier for floating point here gives two positions after the decimal point, with no scientific exponent (e10).
Parse a double, then format the double. BigDecimal.toString() provides a canonical representation:
// Double.parseDouble() also accepts format like "1.574e10"
String formatted = new BigDecimal(Double.valueOf("1.574e10")).toString()
Result:
15740000000
About nicely formatting floating point numbers, see:
How to nicely format floating numbers to String without unnecessary decimal 0?
I'm doing a project where I need to save some user input as a double, formatted to 4 decimal places. I can manage to get the string to have the right format, but parsing it to a Double breaks it. Here is an example of what i'm doing..
DecimalFormat format = new DecimalFormat("#.0000");
String example = "1.23";
Double num = Double.parseDouble(example);
String str = format.format(num);
Double num1 = Double.parseDouble(str);
System.out.println(num1);
this prints
1.23
when i'd like it to print
1.2300
You're confusing the number with the String representation of the number. These are two very different things. A floating point number has an accuracy, but it doesn't understand what display significant digits mean. It's like asking the abstract number 0 to know that 00 is.
To display the number correctly, use the formatter that you have already created:
System.out.println(format.format(num1));
I'm programming a simple java program. I need to get a string from input and divide it into two parts: 1-double 2-string.
Then I need to do a simple calculation on the double and send the result to the output with specific precision(4). It works fine, but there is a problem when the input is 0, then it doesn't work properly.
For example for these input, output will be:
1 kg
output:2.2046
3.1 kg
output:6.8343
But when the input is 0, the output should be 0.0000, but it shows 0.0 .
What should I do to force it to show 0.0000?
I read similar post about double precision, they suggest something like BigDecimal class, but I can't use them in this case,
my code for doing this is:
line=input.nextLine();
array=line.split(" ");
value=Double.parseDouble(array[0]);
type=array[1];
value =value*2.2046;
String s = String.format("%.4f", value);
value = Double.parseDouble(s);
System.out.print(value+" kg\n");
DecimalFormat will allow you to define how many digits you want to display. A '0' will force an output of digits even if the value is zero, whereas a '#' will omit zeros.
System.out.print(new DecimalFormat("#0.0000").format(value)+" kg\n"); should to the trick.
See the documentation
Note: if used frequently, for performance reasons you should instantiate the formatter only once and store the reference: final DecimalFormat df = new DecimalFormat("#0.0000");. Then use df.format(value).
add this instance of DecimalFormat to the top of your method:
DecimalFormat four = new DecimalFormat("#0.0000"); // will round and display the number to four decimal places. No more, no less.
// the four zeros after the decimal point above specify how many decimal places to be accurate to.
// the zero to the left of the decimal place above makes it so that numbers that start with "0." will display "0.____" vs just ".____" If you don't want the "0.", replace that 0 to the left of the decimal point with "#"
then, call the instance "four" and pass your double value when displaying:
double value = 0;
System.out.print(four.format(value) + " kg/n"); // displays 0.0000
System.out.format("%.4f kg\n", 0.0d) prints '0.0000 kg'
I suggest you to use the BigDecimal class for calculating with floating point values. You will be able to control the precision of the floating point arithmetic. But back to the topic :)
You could use the following:
static void test(String stringVal) {
final BigDecimal value = new BigDecimal(stringVal).multiply(new BigDecimal("2.2046"));
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(4);
df.setMinimumFractionDigits(4);
System.out.println(df.format(value) + " kg\n");
}
public static void main(String[] args) {
test("0");
test("1");
test("3.1");
}
will give you the following output:
0,0000 kg
2,2046 kg
6,8343 kg
String.format is just makign a String representation of the floating point value. If it doesnt provide a flag for a minimum precision, then just pad the end of the string with zeros.
Use DecimalFormat to format your double value to fixed precision string output.
DecimalFormat is a concrete subclass of NumberFormat that formats
decimal numbers. It has a variety of features designed to make it
possible to parse and format numbers in any locale, including support
for Western, Arabic, and Indic digits. It also supports different
kinds of numbers, including integers (123), fixed-point numbers
(123.4), scientific notation (1.23E4), percentages (12%), and currency
amounts ($123). All of these can be localized.
Example -
System.out.print(new DecimalFormat("##.##").format(value)+" kg\n");
In Java, I am trying to parse a string of format "###.##" to a float. The string should always have 2 decimal places.
Even if the String has value 123.00, the float should also be 123.00, not 123.0.
This is what I have so far:
System.out.println("string liters of petrol putting in preferences is " + stringLitersOfPetrol);
Float litersOfPetrol = Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));
System.out.println("liters of petrol before putting in editor: " + litersOfPetrol);
It prints:
string liters of petrol putting in preferences is 010.00
liters of petrol before putting in editor: 10.0
This line is your problem:
litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));
There you formatted your float to string as you wanted, but but then that string got transformed again to a float, and then what you printed in stdout was your float that got a standard formatting. Take a look at this code
import java.text.DecimalFormat;
String stringLitersOfPetrol = "123.00";
System.out.println("string liters of petrol putting in preferences is "+stringLitersOfPetrol);
Float litersOfPetrol=Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
stringLitersOfPetrol = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : "+stringLitersOfPetrol);
And by the way, when you want to use decimals, forget the existence of double and float as others suggested and just use BigDecimal object, it will save you a lot of headache.
Java convert a String to decimal:
String dennis = "0.00000008880000";
double f = Double.parseDouble(dennis);
System.out.println(f);
System.out.println(String.format("%.7f", f));
System.out.println(String.format("%.9f", new BigDecimal(f)));
System.out.println(String.format("%.35f", new BigDecimal(f)));
System.out.println(String.format("%.2f", new BigDecimal(f)));
This prints:
8.88E-8
0.0000001
0.000000089
0.00000008880000000000000106383001366
0.00
Use BigDecimal:
new BigDecimal(theInputString);
It retains all decimal digits. And you are sure of the exact representation since it uses decimal base, not binary base, to store the precision/scale/etc.
And it is not subject to precision loss like float or double are, unless you explicitly ask it to.
I just want to be sure that the float number will also have 2 decimal places after converting that string.
You can't, because floating point numbers don't have decimal places. They have binary places, which aren't commensurate with decimal places.
If you want decimal places, use a decimal radix.
litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));
System.out.println("liters of petrol before putting in editor : "+litersOfPetrol);
You print Float here, that has no format at all.
To print formatted float, just use
String formatted = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : " + formatted);
Float.parseFloat() is the problem as it returns a new float.
Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class Float.
You are formatting just for the purpose of display . It doesn't mean the float will be represented by the same format internally .
You can use java.lang.BigDecimal.
I am not sure why are you using parseFloat() twice. If you want to display the float in a certain format then just format it and display it.
Float litersOfPetrol=Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
System.out.println("liters of petrol before putting in editor"+df.format(litersOfPetrol));
How to set the output format lat and lng like this: 0.000000?
double lat = marker.getPosition().latitude;
double lng = marker.getPosition().longitude;
Preferably without converting to a String, so that the output is a double.
No numbers in Java have any kind of output format associated with them. To output them at all, they are converted to a String, even if you call System.out.println(marker.getPosition().latitude).
It is possible to format a double, like any number, but only when converting to a String.
You can use DecimalFormat:
DecimalFormat df = new DecimalFormat("0.000000");
String formattedLat = df.format(marker.getPosition().latitude);
(The 0 is necessary instead of # to make trailing zeroes show up.)
It is also possible to use String.format().
But conversion to a String is necessary if you want to format the number.
You can try this method to round to 6 decimal places using DecimalFormat
double roundDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("0.000000");
return Double.valueOf(twoDForm.format(d));
}
use like:
double lat = roundDecimals(marker.getPosition().latitude);
double lng = roundDecimals(marker.getPosition().longitude);
The link posted by #TronicZomB has more relevant information and is a good read.