import java.math.RoundingMode;
public class DecimalFormat
{
public static void main(String[] args)
{
java.text.DecimalFormat df = new java.text.DecimalFormat("#.######E0");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println(df.format(3));
System.out.println(df.format(19.346346436));
}
}
output is:
3E0
1.934635E1
Is there any way where i can change 3E0 to just 3 without changing 1.934635E1?
CodePudding user response:
You can check for Integer before formatting like below :
lets assume y is our variable containing numerical value
double y=25.33;
java.text.DecimalFormat df = new java.text.DecimalFormat("#.######E0");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println(y == (int)y ? (int)y: df.format(y));
You can put integer value as well in variable y to get the desired output. I hope this help.
CodePudding user response:
I would write a custom format that handles long
and double
inputs differently. Something like this (not intended as a complete custom format, just a demonstration):
public class SO_73377546 {
public static void main(String[] args) {
NumberFormat df = new CustomFormat("#.######E0", RoundingMode.CEILING);
System.out.println(df.format(3));
System.out.println(df.format(19.346346436));
}
}
class CustomFormat extends NumberFormat {
private DecimalFormat standardFormat;
private DecimalFormat scientificFormat;
public CustomFormat(String pattern, RoundingMode roundingMode) {
this.standardFormat = new DecimalFormat("#");
this.scientificFormat = new DecimalFormat(pattern);
scientificFormat.setRoundingMode(roundingMode);
}
@Override
public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
return scientificFormat.format(number, toAppendTo, pos);
}
@Override
public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) {
return standardFormat.format(number, toAppendTo, pos);
}
@Override
public Number parse(String source, ParsePosition parsePosition) {
// TODO: Untested
return scientificFormat.parse(source, parsePosition);
}
}
When run, this produces the following output:
3
1.934635E1