DecimalFormat pattern for BigDecimal. - java

What pattern of DecimalFormat should I use so that when I format BigDecimals like
new BigDecimal("4235886589.00000");
new BigDecimal("4235886589.0000030000");
new BigDecimal("4235886589.0");
new BigDecimal("4235886589");
The output must have the following appearance:
4,235,886,589.00000; 4,235,886,589.0000030000; 4,235,886,589.0; 4,235,886,589;
So basically I'm trying to write a pattern which won't cut off zeros in the end and won't put them if they are not necessary. I tried to handle it with patterns:
DecimalFormat formatter = new DecimalFormat("#,###,##0.########");
DecimalFormat formatter = new DecimalFormat("#,###,##0.000000");
But the first formatter cuts off zeros, whereas the second one puts them where they are unnecessary.

I don't think you can do it in a straight way using the formatter. What you can do is wrap your Decimal in a class where you can store the appropriate format string computed at instantiation:
class MyBigDecimal {
String asString;
BigDecimal n;
public MyBigDecimal(String asString) {
this.asString = asString;
n = new BigDecimal(asString);
}
}

Related

Convert double value to contain decimal seperator and only two digits after comma in groovy

I would like to convert a number such as the following:
2937998.7397271004
to look like this:
2.937.998,73
My attempt of achieving this looks as following, but the result still looks the same:
DecimalFormat decimalFormat = new DecimalFormat("###.###.###.###,00");
def val = decimalFormat.format(cell.getNumericCellValue().doubleValue())
return val
One way to do is to use a locale which supports your formatting pattern. For example Locale.GERMAN is in line with what you are expecting
DecimalFormat df = new DecimalFormat("###,###.00",
DecimalFormatSymbols.getInstance(Locale.GERMAN));
df.format(2937998.7397271004); // 2.937.998,74
You should definitely use Locale for this issue. And in your case formatting is german:
import java.text.NumberFormat
NumberFormat numberFormat = NumberFormat.getInstance(Locale.GERMAN);
println numberFormat.format(2937998.7397271004)
Although I am not familiar with groovy as far as I know it still utilizes the java libraries.
You cannot utilize multipled .'s on a standard DecimalFormat as can be seen in the documentation for the java class: Documentation.
So the following line of code needs to changed to:
DecimalFormat decimalFormat = new DecimalFormat("###,###,###,###.00");
Which will respond with 2.937.998,74 utilizing the provided value of 2937998.7397271004.
If you want to do it as 2.937.998,74 you can, again at least in java, do the following.
DecimalFormat decimalFormat = new DecimalFormat("###,###,###,###.00");
DecimalFormatSymbols custom = new DecimalFormatSymbols();
custom.setDecimalSeparator(',');
custom.setGroupingSeparator('.');
decimalFormat.setDecimalFormatSymbols(custom);
String val = decimalFormat.format(cell.getNumericCellValue().doubleValue());
Or use the locale as other aswers sugest.

how to format a string value to double decimal format

Number Format nf = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("$###,###.###");
String format_val=df.format(4596.37);
num = new jxl.write.Number(i, j,Double.parseDouble(format_val),arial10format);
here I'm getting NumberFormatException :
java.lang.NumberFormatException: For input string: "$4,596.37"
how to solve this one?
What I "think" you want (I've not tried this) is to let the cell take care of the formatting, for example...
NumberFormat decimalNo = new NumberFormat("$###,###.###");
WritableCellFormat numberFormat = new WritableCellFormat(decimalNo);
//write to datasheet
Number numberCell = new Number(i, j, 4596.37, numberFormat);
excelSheet.addCell(numberCell);
Take a look at WritableCellFormat for more details
What you've tried to do is...
Convert the double value 4596.37 to a String, with the format of $###,###.###
Try and convert $4,596.37 back to a double...which fails as the String you've passed to does not conform to the requirements of a double...
A number has no concept of format, that's what formatters are for. In this case, however, the Excel cell has it's own internal formatting capabilities which can take care of this for you
you can use the same DecimalFormat instance you used to create the string to parse it too by using the parse() method
see the javaDoc for more details
http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html#parse(java.lang.String,%20java.text.ParsePosition)

Formatting numbers using DecimalFormat

I am trying to format prices using DecimalFormat, but this isn't working for all variations.
DecimalFormat df = new DecimalFormat("0.##")
df.format(7.8)
df.format(85.0)
prints
7.80
and
85
but "7.79999" gets formatted as "7.8", not "7.80". I have tried doing things this way
DecimalFormat df = new DecimalFormat("0.00")
to force two dp, but then "85.0" gets formatted as "85.00" not "85"!
Is there a way of capturing all variations, so that prices are printed either as #, ##, or #.##? For example:
5, 55, 5.55, 5.50, 500, 500.40
There is a slight difference between these two formats. The "#.##" means it will print the number with maximum two decimal places whereas "#.00" means it will always display two decimal places and if the decimal places are less than two, it will replace them with zeros. see the example below with output.
public static final DecimalFormat df1 = new DecimalFormat( "#.##" );
public static final DecimalFormat df2 = new DecimalFormat( "#.00" );
System.out.println(df1.format(7.80));
System.out.println(df1.format(85));
System.out.println(df1.format(85.786));
System.out.println(df2.format(7.80));
System.out.println(df2.format(85));
System.out.println(df2.format(85.786));
And the output will be
7.8
85
85.79
7.80
85.00
85.79
This doesn't seem to be solved by a single formatter. I suggest you use "0.00" format and replace ".00" with an empty string.
public static String myFormat(double number) {
DecimalFormat df = new DecimalFormat("0.00");
return df.format(number).replaceAll("\\.00$", "");
}
I don't think it's possible, at least not with Java SE formatters. You need to make a custom formatter. I would do it like this
String res = df.format(number).replace(".00", "");
Use the BigDecimal number class instead:
e.g. if n is a BigDecimal,
then you can use
String s = NumberFormat.getCurrencyInstance().format(n);
By the way, it's best practice to use BigDecimal when working with money.
You can try with:
DecimalFormat df = new DecimalFormat("#.##",new DecimalFormatSymbols(Locale.US));
System.out.println(new java.text.DecimalFormat("#.##").format(5.00));
This will print 5
System.out.println(new java.text.DecimalFormat("#.00").format(500.401));
This will print 500.40

Howto format number with DecimalFormat with optional scientific notation

I am using a pattern "#0.00##" to format numbers, it works as expected for most input. But sometimes sources number are smaller ie: 6.84378E-05, and gets converted into "0,0001".
Is it possible to format only such numbers (not fitting standard pattern) using scientific notation? leaving all "normal" numbers intact? with single pattern.
I have to use only a single DecimalFormat pattern, without any extra code.
EDIT: To better explain why I need single DecimalFormat : I am using an external library and can only define a pattern to configure output.
You can have distinct patterns only for positive and negative values.You should do something like:
public class DecimalScientificFormat extends DecimalFormat {
private static DecimalFormat df = new DecimalFormat("#0.00##");
private static DecimalFormat sf = new DecimalFormat("0.###E0");
#Override
public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition) {
String decimalFormat = df.format(number);
return (0.0001 != number && df.format(0.0001).equals(decimalFormat)) ? sf.format(number, result, fieldPosition) : result.append(decimalFormat);
}
}

How to convert a string 3.0103E-7 to 0.00000030103 in Java?

How to convert a string 0E-11 to 0.00000000000 in Java? I want to display the number in non scientific notations. I've tried looking at the number formatter in Java, however I need to specific the exact number of decimals I want but I will not always know. I simply want the number of decimal places as specificed by my original number.
Apparently the correct answer is to user BigDecimal and retrieve the precision and scale numbers. Then use those numbers in the Formatter. Something similar like this:
BigDecimal bg = new BigDecimal(rs.getString(i));
Formatter fmt = new Formatter();
fmt.format("%." + bg.scale() + "f", bg);
buf.append( fmt);
Using BigDecimal:
public static String removeScientificNotation(String value)
{
return new BigDecimal(value).toPlainString();
}
public static void main(String[] arguments) throws Exception
{
System.out.println(removeScientificNotation("3.0103E-7"));
}
Prints:
0.00000030103
I would use BigDecimal.Pass your string into it as a parameter and then use String.format to represent your newly created BigDecimal without scientific notation.
Float or Double classes can be used too.
double d = Double.parseDouble("7.399999999999985E-5");
NumberFormat formatter = new DecimalFormat("###.#####");
String f = formatter.format(d);
System.out.println(f); // output --> 0.00007
I haven't tried it, but java.text.NumberFormat might do what you want.

Categories