I retrieve from an XML file a float number that I want to format and insert in a text file with the pattern 8 digits after comma, and 2 before.
Here is my code:
String patternNNDotNNNNNNNN = "%11.8f";
float value = 1.70473711f;
String result = String.format(java.util.Locale.US, patternNNDotNNNNNNNN, value);
System.out.println(result);
As a result I get: 1.70473707
Same problem if I use:
java.text.DecimalFormatSymbols symbols = new java.text.DecimalFormatSymbols(java.util.Locale.US);
java.text.DecimalFormat df = new java.text.DecimalFormat("##.########", symbols);
System.out.println(df.format(value));
I don't understand why I have a rounded value (1.70473711 comes to 1.70473707).
This is because the precision of the float means that the value 1.7043711 is not actually 1.7043711.
Consider the following which process 1.70473711f as both a float and a double:
String patternNNDotNNNNNNNN = "%11.8f";
float valueF = 1.70473711f;
String result = String.format(java.util.Locale.US, patternNNDotNNNNNNNN, valueF);
System.out.println(valueF);
System.out.println(result);
double valueD = 1.70473711f;
result = String.format(java.util.Locale.US, patternNNDotNNNNNNNN, valueD);
System.out.println(valueD);
System.out.println(result);
Output:
1.7047371
1.70473707
1.7047370672225952
1.70473707
When treating the value as a double, you can see that 1.7043711f is actually 1.7047370672225952. Rounding that to 8 places gives 1.70473707 and not 1.70473711 as expected.
Instead, treat the number as a double (i.e. remove the f) and the increase precision will result in the expected output:
double valueD = 1.70473711;
String result = String.format(java.util.Locale.US, patternNNDotNNNNNNNN, valueD);
System.out.println(valueD);
System.out.println(result);
Output:
1.70473711
1.70473711
String.format on floating point values does round them. If you don't want that, use BigDecimal. See
double d = 0.125;
System.out.printf("%.2f%n", d);
Related
I'm still new to Java and I was wondering if there are any ways to format to a double without having it rounded?
Example:
double n = 0.12876543;
String s = String.format("%1$1.2f", n);
If I were to print to the system, it would return the 0.13 instead of the precise 0.12. Now I have thought of a solution but I want to know if there is a better way of doing this. This my simple solution:
double n = 0.12876543;
double n = Double.parseDouble(String.format(("%1$1.2f", n));
Any other thoughts or solutions?
An elegant solution would be to use setRoundingMode with DecimalFormat. It sets the RoundingMode appropriately.
For example:
// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Print statement
System.out.println(curDf.format(n));
Output:
0.12
Further, if you want to do additional formatting as a string you can always change the double value into string:
// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Convert to string for any additional formatting
String curString = String.valueOf(curDf.format(n));
// Print statement
System.out.println(curString);
Output:
0.12
Please refer similar solution here: https://stackoverflow.com/a/8560708/4085019
As is, rounded to 2 decimals and truncated to 2 decimals :
double n = 0.12876543;
String complete = String.valueOf(n);
System.out.println(complete);
DecimalFormat df = new DecimalFormat("#.##");
String rounded = df.format(n);
System.out.println(rounded);
df.setRoundingMode(RoundingMode.DOWN);
String truncated = df.format(n);
System.out.println(truncated);
it displays :
0.12876543
0.13
0.12
Your example is working correctly in that it is properly rounding the number to 2 decimal places. 0.12876543 properly rounds to 0.13 when rounded to 2 decimal places. However, it seems like you always want to round the number down? If that is the case then you can do something like this...
public static void main(String[] args) throws IOException, InterruptedException {
double n = 0.12876543;
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.DOWN);
String s = df.format(n);
System.out.println(s);
}
This will print out a value of 0.12
Note first that a double is a binary fraction and does not really have decimal places.
If you need decimal places, use a BigDecimal, which has a setScale() method for truncation, or use DecimalFormat to get a String.
I want to add zero before decimal, if the number starts with decimal itself.
Input: .2345
Output: 0.2345
I'm using DecimalForamtter. I'm avoiding using string appender.
Please suggest.
Thank You
that should give you the expected output:
#Test
public void testFloatLeadingZero(){
float value = .1221313F;
DecimalFormat lFormatter = new DecimalFormat("##0.0000");
String lOutput = lFormatter.format(value);
Assert.assertTrue(lOutput.startsWith("0."));
}
or with String.format:
#Test
public void testFloatLeadingZero(){
float value = .1221313F;
String lOutput = String.format("%.20f", value);
Assert.assertTrue(lOutput.startsWith("0."));
double value2 = .1221313d;
String lOutput2 = String.format("%.20d", value2);
Assert.assertTrue(lOutput2.startsWith("0."));
}
I think you are using Float right? Otherwise you have to replace f with d for Double.
I have used below code and worked in all scenarios. I wanted to get 10 digits including 2 decimal places. It will give me trailing 0s in decimal place also.
DecimalFormat df = new DecimalFormat("00000000.00");
double d1 = 678.90;
System.out.println(df.format(d1));
Output: 00000678.90
I want to round the decimal values of string.below is the example
String Result = "19292.5"
i want the output of result to round to 19292
In short i want to remove the ending .5 decimal value.
Result = Result.substring(0, Result.indexOf("."));
System.out.println(Result);
You could use substring to hack off everything after the ".".
How about this?
String result = "19292.5";
int intValue = Double.valueOf(result).intValue();
If you need to round/floor a double value, you can use the Math class:
String result = "19292.5";
double rounded = Math.round(Double.valueOf(result));
double floored = Math.floor(Double.valueOf(result));
I am trying to convert a String number to two decimal places in Java. I saw lot of posts on satckoverflow but somehow I am getting an exception.
String number = "1.9040409535344458";
String result = String.format("%.2f", number);
System.out.println(result);
This is the exception I am getting -
java.util.IllegalFormatConversionException: f != java.lang.String
I would like to have 1.904 as the output. Does anyone know what wrong I am doing here?
You can try using a NumberFormat. For example:
String number = "1.9040409535344458";
NumberFormat formatter = new DecimalFormat("#0.000");
String result = formatter.format(Double.valueOf(number));
System.out.println(result);
Just declare number to be double :
Double number = 1.9040409535344458;
instead of
String number = "1.9040409535344458";
OUTPUT :
1.90
you should first convert the string into double and then change the decimal value
String number = "1.9040409535344458";
double result = Double.parseDouble(number);//converts the string into double
result = result *100;//adjust the decimal value
System.out.println(result);
You are using a format not meant for a String. I would recommend either converting your String to a double or storing it as a double in the first place. Convert the String to a double, and pass that double to String.format.
Is there a simple way in Java to format a decimal, float, double, etc to ONLY print the decimal portion of the number? I do not need the integer portion, even/especially if it is zero!
I am currently using the String.indexOf(".") method combined with the String.substring() method to pick off the portion of the number on the right side of the decimal. Is there a cleaner way to do this? Couldn't find anything in the DecimalFormat class or the printf method. Both always return a zero before the decimal place.
You can remove the integer part of the value by casting the double to a long. You can then subtract this from the original value to be left with only the fractional value:
double val = 3.5;
long intPartVal= (long) val;
double fracPartVal = val - intPartVal;
System.out.println(fracPartVal);
And if you want to get rid of the leading zero you can do this:
System.out.println(("" + fracPartVal).substring(1));
Divide by 1 and get remainder to get decimal portion (using "%"). Use DecimalFormat to format result (using "#" symbol to suppress leading 0s):
double d1 = 67.22;
double d2 = d1%1;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(d2));
this prints .22
This will print 0.3
double x = 23.8;
int y =(int)x;
float z= (float) (x % y);
System.out.println(z);