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));
Related
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);
I want to create a String from a double value with 10 character for example
Double d = 150.23;
The output string like this 0000015023+
I have used this code but it is not working:
String imponibile = String.format("%10d%n", myDoubleValue);
You want to print 150.23 without the period. Formatting is not supposed to achieve that. You have to:
transform the double number to a int number with the desired rounding and print the int:
int i = (int) Math.round(100.0 * d);
String.format("%010d", i)
Where "010" means print at least 10 digits and pad with zero if there are less. The padding char going before the number of digits.
print the double and remove the period from the string afterwards:
String.format("%011.2f", d).replace(".", "")
Note how you now have to specify 11 including the period. And you have to specify the number of digits after the period
I don't think there is a way to print the sign after a number with String.format. You can easily require to print it at the start which is the normal way to print numbers:
String s = String.format("%+010d", i);
And if you must you can use substring and concatenation to put it at the end:
String imponibile = s.substring(1) + s.charAt(0);
Try f instead of d:
String imponibile = String.format("%010.0f", myDoubleValue*100);
Floating Point - may be applied to Java floating-point types: float,
Float, double, Double, and BigDecimal
Class Formatter
When i execute the below code:
public class Test {
public static void main(String args[]){
DecimalFormat format = new DecimalFormat();
Double value = new Double(-1350825904190559999913623552.00);
StringBuffer buffer = new StringBuffer();
FieldPosition position = new FieldPosition(0);
format.format(new BigDecimal(value), buffer, position);
System.out.println(buffer);
}
}
This correctly prints -1,350,825,904,190,559,999,913,623,552.
I have code which does go through a lot of doubles so I dont want the conversion from double to bigdecimal. I figured the processing time for BigDecimal is large.
So i do format.format(value, buffer, position)
And i see the precision is lost.
The output I get is -1,350,825,904,190,560,000,000,000,000.
What am i doing wrong here? Is there a better way to deal with this and still retain the precision. I don't want to deal with BigDecimals here but just work with the decimals.
Any suggestions?
double doesn't have infinite precision, and you can't gain more precision than a double has by converting a double to a BigDecimal (like you can't gain more precision with an int when you do double r = 1/3; which is 0.0 because it widens an int to a double). Instead, you could use a String. Something like
DecimalFormat format = new DecimalFormat();
String value = "-1350825904190559999913623552.00";
System.out.println(format.format(new BigDecimal(value)));
It isn't lost during formatting. It is lost right here:
Double value = new Double(-1350825904190559999913623552.00);
A double only has about 15.9 significant decimal digits. It doesn't fit. There was a precision loss at compile time when the floating-point literal was converted.
The issue is in the output formatting, specifically how doubles are converted to strings by default. Each double number has an exact value, but it is also the result of string to double conversion for a range of decimal fractions. In this case, the exact value of the double is -1350825904190559999913623552, but the range is [-1350825904190560137352577024,-1350825904190559862474670080].
The Double toString conversion picks the number from that range with the fewest significant digits, -1.35082590419056E27. That string does convert back to the original value.
If you really want to see the exact value, not just enough digits to uniquely identify the double, your current BigDecimal approach works well.
Here is the program I used to calculate the numbers in this answer:
import java.math.BigDecimal;
public class Test {
public static void main(String args[]) {
double value = -1350825904190559999913623552.00;
/* Get an exact printout of the double by conversion to BigDecimal
* followed by BigDecimal output. Both those operations are exact.
*/
BigDecimal bdValue = new BigDecimal(value);
System.out.println("Exact value: " + bdValue);
/* Determine whether the range is open or closed. The half way
* points round to even, so they are included in the range for a number
* with an even significand, but not for one with an odd significand.
*/
boolean isEven = (Double.doubleToLongBits(value) & 1) == 0;
/* Find the lower bound of the range, by taking the mean, in
* BigDecimal arithmetic for exactness, of the value and the next
* exactly representable value in the negative infinity direction.
*/
BigDecimal nextDown = new BigDecimal(Math.nextAfter(value,
Double.NEGATIVE_INFINITY));
BigDecimal lowerBound = bdValue.add(nextDown).divide(BigDecimal.valueOf(2));
/* Similarly, find the upper bound of the range by going in the
* positive infinity direction.
*/
BigDecimal nextUp = new BigDecimal(Math.nextAfter(value,
Double.POSITIVE_INFINITY));
BigDecimal upperBound = bdValue.add(nextUp).divide(BigDecimal.valueOf(2));
/* Output the range, with [] if closed, () if open.*/
System.out.println("Range: " + (isEven ? "[" : "(") + lowerBound + ","
+ upperBound + (isEven ? "]" : ")"));
/* Output the result of applying Double's toString to the value.*/
String valueString = Double.toString(value);
System.out.println("toString result: " + valueString);
/* And use BigDecimal as above to print the exact value of the result
* of converting the toString result back again.
*/
System.out.println("exact value of toString result as double: "
+ new BigDecimal(Double.parseDouble(valueString)));
}
}
Output:
Exact value: -1350825904190559999913623552
Range: [-1350825904190560137352577024,-1350825904190559862474670080]
toString result: -1.35082590419056E27
exact value of toString result as double: -1350825904190559999913623552
You cannot represent 1350825904190559999913623552.00 accurately with a Double. If you would like to know why, explore this article.
Should you want to represent the value, I would advise using the code you have used in your question: new BigDecimal( value ), where value is actually a String representation.
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);