Java - Format number to print decimal portion only - java

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);

Related

How to print formatted double value to string in java?

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

Java convert a format.String

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.

Java DecimalFormat losing precision while formatting double

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.

Java Double to String with dot separator and infinite number of digits after the decimal

I want to parse a java double value to string but with dot separator and infinite number of digits after the decimal. What I want to achived:
33.123456789 -> "33.123456789"
1.234 -> "1.234"
2.0 -> "2"
I have my sample code but it doesn't work corectly.
DecimalFormat DOUBLE_FORMAT = (DecimalFormat)NumberFormat.getNumberInstance(Locale.ENGLISH);
DOUBLE_FORMAT.applyPattern("#.####");
Which gives me:
33.123456789 -> "33.1234"
1.234 -> "1.234"
2.0 -> "2"
So it not work how I want to. Any idea ? ;)
Doubles are just an approximation, a sum of 2-i. Hence
33.123456789 * 100 != 3312.3456789
And
double x = 33.123456789;
String s = String.valueOf(x);
// No guarantee that s has the same number of decimals.
And for the precise numerical type BigDecimal:
BigDecimal x = new BigDecimal(33.123456789); // Bad
BigDecimal x = new BigDecimal("33.123456789"); // Good, with correct precision.
So in your case, one must consider switching to BigDecimal. Or accept String.valueOf / Double.toString.
BigDecimal, though, has that unlimited precision.
Just add more #,i.e.
DOUBLE_FORMAT.applyPattern("#.######################");
Why don't you just use BigDecimal and pass it String.valueOf.
double d = 123456789.0;
System.out.println(new BigDecimal(String.valueOf(d)).toPlainString());
double dd = 33.123456789;
System.out.println(new BigDecimal(String.valueOf(dd)).toPlainString());
Output
123456789
33.123456789

Formatting 2 decimal places in java

here's my example:
double num = 0;
num = 4/3;
System.out.println(num);
And my output is 1.0 instead of 1.3
Any suggestions?
Don't do int division since this always will result in a truncated int. Instead have your division use at least one double value.
double num = 4.0/3.0;
Then when you want to display it as a String, format the output so you can choose your decimal places:
// one way to do it
// %.3f is for a floating number with 3 digits to the right of the decimal
// %n is for new line
System.out.printf(%.3f%n, num);
Another:
DecimalFormat decimalFormat = new DecimalFormat("0.000");
System.out.println(decimalFormat.format(num));
Write
num=(double)4/3;
It will return 1.3333....
Then you can round off the decimals
You should also use String.format(%1.2f, yourDouble) to format your decimal places
Try this..
double value= 255.956666;
BigDecimal bd = new BigDecimal(value).setScale(2, RoundingMode.HALF_UP);
System.out.println("value="+bd);

Categories