Convert String to Double with specific format [duplicate] - java

I am using Poi to create Excel workbooks in Java. My raw data comes in as a string. I need to format the data to enter two decimal places into the cell where the number is being written. I use Double.parseDouble() to convert the string to numeric and then use DecimalFormat to format the numeric as a string. Another call to Double.parseDouble() to return the value to numeric (the cell where it is going is formatted numeric, so I can't use the string value) and I should be good. Problem is, that second call to Double.parseDouble() truncates any trailing zeroes off from the right of the decimal point. Anybody have an idea as to how I can coerce this value to read as, say, 1.50 rather than 1.5?

I always want two decimals.
Solution: Always apply specific decimal format pattern.
Sample code snippet:
//java.text.DecimalFormat df = new java.text.DecimalFormat( "###0.00" );
java.text.DecimalFormat df = new java.text.DecimalFormat();
df.applyPattern( "###0.00" ); // always two decimals
double dbl = 1.50d ;
// prints: dbl = 1.5
System.out.println( "dbl = " + dbl );
// prints: df.format( 1.5 ) = 1.50
System.out.println ( "df.format( " + dbl + " ) = " + df.format( dbl ) );
UPDATE:
OK, from your posting, I understand that you are trying to fill the numeric formatted cell only to print or show up with two decimal positions. You know by default all numeric fields are interpreted omitting trailing zeros. To achieve your requirement, you may require to use CellFormat and/or DataFormatter on your contextual Cell object, but when said Format, it is a String again.
I didn't try the following code but may help you.
DataFormatter dataFormatter = new DataFormatter();
dataFormatter.setDefaultNumberFormat( instanceOfDesiredDecimalFormat );
// or
// dataFormatter.setExcelStyleRoundingMode( instanceOfDesiredDecimalFormat );
// apply this format on the cell you want
dataFormatter.formatCellValue( instanceOfNumericCellInContext );

You are actually doing nothing in most part of the code you described. You might as well just return Double.parseDouble(inputString). Doubles are stored in binary format and the leadin/trailing zeros make no sense. Perhaps the BigDecimal class is something for you.

It appears we are at an impasse. As Mario pointed out, doubles are managed as binary and there is no way to format the binary as a double, except to convert it to a string with DecimalFormat, which is no longer a double. I explained this to my boss and he's ok with the solution of taking the raw double, so I'm closing this issue. Thanks to all for your help and support.
regards,
Mike

Related

Change Double format - dot to comma

I must change Double format from dot to comma. I try this:
DecimalFormat df = new DecimalFormat("#,00",
DecimalFormatSymbols.getInstance(Locale.GERMANY));
selectedSheet.addCell(new Number(selectedCellColumn,
selectedCellRow,
Double.valueOf(df.format(value)));
but it`s not working. Have you got any ideas how you can change a dot to a comma?
For (i guess) ApachePOI library to set a different CellUnitStyle use this:
CellStyle unitStyle = workbook.createCellStyle();
unitStyle.setDataFormat((short) BuiltinFormats.getBuiltinFormat("#,##0.00"));
cell.setCellValue(value);
cell.setCellStyle(unit);
Following Formats are builtin available:
ApachePOI builtin Formats
new Number() - I assume this takes double as the third argument? In that case, formatting the double value before you pass it in there is impossible, you need to set the format on how the sheet will display numbers in the cell formatting settings.
Or is the problem that you have a string like "5,3" and want to convert it to double? It looks like the varaible value already has a double value in it.
You have a symbol table in the java doc of DecimalFormat:
Symbol Location Localized? Meaning
------------------------------------------
0 Number Yes Digit
# Number Yes Digit, zero shows as absent
. Number Yes Decimal separator or monetary decimal separator
- Number Yes Minus sign
, Number Yes Grouping separator
etc...
You were using the grouping separator , but you wanted to use the decimal separator ., so change your string from #,00 to #.00:
DecimalFormat df = new DecimalFormat("#.00", DecimalFormatSymbols.getInstance(Locale.GERMANY));
String format = df.format(3.23456);
System.out.println(format); // prints 3,23
Code :
double value = 123.12345;
DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance(Locale.GERMANY);
decimalFormatSymbols.setDecimalSeparator(',');
DecimalFormat df = new DecimalFormat("#.###", decimalFormatSymbols);
System.out.println(df.format(value));
selectedSheet.addCell(new Number(selectedCellColumn, selectedCellRow, Double.valueOf(df.format(value)));
Output :
123,123

What is the MessageFormat pattern to produce localized, full precision output for any double

Given the example code:
String format = "{0,number}"; // <- What do I put here?
double value = Math.PI * 1e-10;
System.out.println(value);
System.out.println(new MessageFormat(format, Locale.US).format(new Object[]{value}));
System.out.println(new MessageFormat(format, Locale.FRANCE).format(new Object[]{value}));
What do I use as the format string such that I get full precision output of any double value and that the output is localized? For example, the output of the current code is:
3.1415926535897934E-10
0
0
String.valueOf(double) correctly prints the full precision, but it isn't a message format and it is not localized. The message format decides the value is too small to bother with. For large numbers the results are even worse! MessageFormat prints 16 significant digits and then appends a bunch of zeros that do not accurately reflect the value stored in the double. E.g. with pi * 1e100 I get:
3.141592653589793E100
31,415,926,535,897,930,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000
31 415 926 535 897 930 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000
For your requirement and only for it, this is an easiest solution which fits to your code.
Using # symbol below, we show the digits only when they are not 0, otherwise they are being omit.
double value = Math.PI*1e-10;
String format = "{0,number,#.###############E0}"; // <- What do I put here?
System.out.println(value);
System.out.println(new MessageFormat(format, Locale.US).format(new Double[]{value}));
System.out.println(new MessageFormat(format, Locale.FRANCE).format(new Double[]{value}));
If you want to omit conversion of formatting numbers using scientific notifications, for example instead of 9.424777960769379E2( if in format #.###############E0) or 94.24777960769379E1 ( if in format ##.###############E0 ) to be 942.4777960769379, just use code below:
double value = Math.PI*1e-10;
String format = "{0,number,#.################}"; // <- What do I put here?
Take a look and if there is something you need additionally, feel free to ask!

Formating big numbers in Java

I have an edittext with a maxlength
My question is...
How can I display the value of a bigger number than the maxlenght like the windows calc??
Example:
1.34223423423434e+32
I want this with the edittext maxlength
EDIT: I want this for display and store numbers without having problems with math operations if it's possible
Thanks
This is what the BigInteger class (or BigDecimal, for non-integers) is for.
These classes store numbers with arbitrary precision, and allow for standard arithmetic operations. You can get the exact value of the number as a string, and then format that as you wish (e.g. trimming the length).
(Note that while it may seem like you can use these classes with a NumberFormat instance, this is not recommended as accuracy will be silently lost if the number doesn't fit into a double.)
Here's an example of using it:
// Create a BigDecimal from the input text
final String numStr = editText.getValue(); // or whatever your input is
final BigDecimal inputNum = new BigDecimal(numStr);
// Alternatievly you could pass a double into the BigDecimal constructor,
// though this might already lose precison - e.g. "1.1" cannot be represented
// exactly as a double. So the String constructor is definitely preferred,
// especially if you're using Double.parseDouble somewhere "nearby" as then
// it's a drop-in replacement.
// Do arithmetic with it if needed:
final BigDecimal result = inputNum.multiply(new BigDecimal(2));
// Print it out in standard scientific format
System.out.println(String.format("%e", result));
// Print it out in the format you gave, i.e. scientific with 14dp
System.out.println(String.format("%.14e", result));
// Or do some custom formatting based on the exact string value of the number
final String resultStr = result.toString();
System.out.println("It starts with " + result.subString(0, 3) + "...");
I'm not sure exactly what format you wanted for output, but whatever it is you should be able to manage it with BigDecimals as the backing store.

Converting exponential value in java to a number format

I am trying to read the values from excel sheet using java. When i type more than 10 letters in a cell in excel it is displaying in exponential form like "9.78313E+2". but this is not the real number what i given.
Can any body help me out in this. How can i convert the above exponential form to original number using java language.
Thanks in advance
You can convert as follows,
for example:
new BigDecimal("406770000244E+12").toBigInteger();
Double.parseDouble("9.78313E+2");
gives me
978.313
For more info see the doc.
Following your further queries below, if you've entered 4256411411 and Excel is presenting this as 4.26E+09, putting that value into parseDouble() will only give you 4260000000. If you want the original, perhaps you need to output the Excel file in a fuller format for your Java program, and/or query it using a Java/Excel API (e.g. POI)
Sorry, but none of the answers above Double.parseDouble() and Double.valueOf()... solved my problem, and I continued to get the exponential 'E' value...
This link has a much better approach for the problem, and as I've written there - there is a very good solution:
I needed to convert some double to currency values, and fount that most to the solution are OK but not for me.
The DecimalFormat was eventually the way for me, so here is what I've done:
public String foo(double value) //Got here 6.743240136E7 or something..
{
DecimalFormat formatter;
if(value - (int)value > 0.0)
formatter = new DecimalFormat("0.00"); //Here you can also deal with rounding if you wish..
else
formatter = new DecimalFormat("0");
return formatter.format(value);
}
As you can see, if the number is natural I get - say - 20000000 instead of 2E7 (etc) - without any decimal point.
and if it's decimal, I get only 2 decimal digits.
Hope this will help.
You can use BigDecimal, if you want the exact value that you have in Excel Sheet: -
BigDecimal bd = new BigDecimal("4256411411");
System.out.println(bd.doubleValue());
// If you are sure that's not a floating point number, then use
System.out.println(bd.longValue());
Prints: -
4.256411411E9
4256411411
Try this definitely gona work
double value = 2.06E //real 205809104.13
BigDecimal.valueOf(value)
work for me
Before you read the value from excel sheet format your Column to number.
This may be helps to you
UPDATED
HSSFCell cellE1 = row1.getCell((short) 4);
cellE1.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
Double e1Val = cellE1.getNumericCellValue();
BigDecimal bd = new BigDecimal(e1Val.toString());
long lonVal = bd.longValue();
System.out.println(lonVal);
You can convert easily with the following methods:
Double.valueOf("9.78313E+2").longValue() or
BigDecimal bd = new BigDecimal("9.78313E+2");
long val = bd.longValue();
Assuming that the given number is in a String form.
You can also use wrapper classes :
Double bd=new Double(4445566622);
System.out.println(bd.longValue());
Outputs -4445566622
i had same problem when i only needed String Data that is "1744949451" but it give "1.744949451E9"
so this worked for me
XSSFCell cell = cells.getCell(j);
String value = cell.toString();
if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
//cell.setCellType(XSSFCell.CELL_TYPE_STRING);
value = cell.getRawValue();
}
Log.i("LOG", value + " " + cell.getCellType());
This answer worked for me:
Double bd = new Double(4445566622);
System.out.println(bd.longValue());
// Outputs -4445566622
`Double value = double value ;
Long longValue = value.longValue(); String strCellValue1 = new String(longValue.toString().format("%f",value).replaceAll("\\,?0*$", ""));`
declare a double value and convert to long
convert to string and formated to float the double value finally replace all the value like 123456789,0000 to 123456789
Have to convert the cell into number format before reading the cell value. Below is the code snippet that is used to get the actual value that is in exponential format:
nextCell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
Double doubleValue = nextCell.getNumericCellValue();
BigDecimal bd = new BigDecimal(doubleValue.toString());
long lonVal = bd.longValue();
String phoneNumber = Long.toString(lonVal).trim();
System.out.print("PhoneNumber " + phoneNumber);
Blog has been wirtten to showcase the actual result.
Regards,
Ankur
Try the following pattern:
Double dblValue = Double.parseDouble("1.99E+07");
String str = String.format("%.2f", dblValue);
System.out.println(str);
Output:
run:
19900000,00
BUILD SUCCESSFUL (total time: 0 seconds)

How can I format a String number to have commas and round?

What is the best way to format the following number that is given to me as a String?
String number = "1000500000.574" //assume my value will always be a String
I want this to be a String with the value: 1,000,500,000.57
How can I format it as such?
You might want to look at the DecimalFormat class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57 instead).
You also need to convert that string into a number, this can be done with:
double amount = Double.parseDouble(number);
Code sample:
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(amount));
This can also be accomplished using String.format(), which may be easier and/or more flexible if you are formatting multiple numbers in one string.
String number = "1000500000.574";
Double numParsed = Double.parseDouble(number);
System.out.println(String.format("The input number is: %,.2f", numParsed));
// Or
String numString = String.format("%,.2f", numParsed);
For the format string "%,.2f" - "," means separate digit groups with commas, and ".2" means round to two places after the decimal.
For reference on other formatting options, see https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Given this is the number one Google result for format number commas java, here's an answer that works for people who are working with whole numbers and don't care about decimals.
String.format("%,d", 2000000)
outputs:
2,000,000
Once you've converted your String to a number, you can use
// format the number for the default locale
NumberFormat.getInstance().format(num)
or
// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)
I've created my own formatting utility. Which is extremely fast at processing the formatting along with giving you many features :)
It supports:
Comma Formatting E.g. 1234567 becomes 1,234,567.
Prefixing with "Thousand(K),Million(M),Billion(B),Trillion(T)".
Precision of 0 through 15.
Precision re-sizing (Means if you want 6 digit precision, but only have 3 available digits it forces it to 3).
Prefix lowering (Means if the prefix you choose is too large it lowers it to a more suitable prefix).
The code can be found here. You call it like this:
public static void main(String[])
{
int settings = ValueFormat.COMMAS | ValueFormat.PRECISION(2) | ValueFormat.MILLIONS;
String formatted = ValueFormat.format(1234567, settings);
}
I should also point out this doesn't handle decimal support, but is very useful for integer values. The above example would show "1.23M" as the output. I could probably add decimal support maybe, but didn't see too much use for it since then I might as well merge this into a BigInteger type of class that handles compressed char[] arrays for math computations.
you can also use the below solution
public static String getRoundOffValue(double value){
DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00");
return df.format(value);
}
public void convert(int s)
{
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(s));
}
public static void main(String args[])
{
LocalEx n=new LocalEx();
n.convert(10000);
}
You can do the entire conversion in one line, using the following code:
String number = "1000500000.574";
String convertedString = new DecimalFormat("#,###.##").format(Double.parseDouble(number));
The last two # signs in the DecimalFormat constructor can also be 0s. Either way works.
Here is the simplest way to get there:
String number = "10987655.876";
double result = Double.parseDouble(number);
System.out.println(String.format("%,.2f",result));
output:
10,987,655.88
The first answer works very well, but for ZERO / 0 it will format as .00
Hence the format #,##0.00 is working well for me.
Always test different numbers such as 0 / 100 / 2334.30 and negative numbers before deploying to production system.
According to chartGPT
Using DecimalFormat:
DecimalFormat df = new DecimalFormat("#,###.00");
String formattedNumber = df.format(yourNumber);
Using NumberFormat:
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setGroupingUsed(true);
String formattedNumber = nf.format(yourNumber);
Using String.format():
String formattedNumber = String.format("%,.2f", yourNumber);
Note: In all the above examples, "yourNumber" is the double value that you want to format with a comma. The ".2f" in the format string indicates that the decimal places should be rounded to 2 decimal places. You can adjust this value as needed.

Categories