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)
Related
I have a double which value is set to 0.00. I need the print statement to display it as "$.00". So the whole number part is not displayed
Tried using String.format() method as well as substring method but it did not bring me anywhere...any help is appreciated, thank you!
I can only think of performing two steps. First format the value to two decimal places. Then use String.substring starting from the decimal place. Like,
double x = 9.99;
String withZero = String.format("%.2f", x);
System.out.printf("$%s%n", withZero.substring(withZero.indexOf('.')));
Outputs (as requested)
$.99
Try this:
public static void outputFractional(double value) {
double whole = Math.abs(value);
double fraction = whole - ((long) whole);
DecimalFormat format = new DecimalFormat("$.00");
System.out.println(format.format(fraction));
}
The simples solution is to use DecimalFormat and set the max number of integer digits to 0.
DecimalFormat formatter = new DecimalFormat("$.00");
formatter.setMaximumIntegerDigits(0);
As I understand the question:
Try that one
double amount = 0;
System.out.println("$" + amount);
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
I'd like to change float like this way:
10.5000 -> 10.5
10.0000 -> 10
How can I delete all zeros after the decimal point, and change it either float (if there's non-zeros) or int (if there were only zeros)?
Thanks in advance.
Why not try regexp?
new Float(10.25000f).toString().replaceAll("\\.?0*$", "")
Well the trick is that floats and doubles themselves don't really have trailing zeros per se; it's just the way they are printed (or initialized as literals) that might show them. Consider these examples:
Float.toString(10.5000); // => "10.5"
Float.toString(10.0000); // => "10.0"
You can use a DecimalFormat to fix the example of "10.0":
new java.text.DecimalFormat("#").format(10.0); // => "10"
java.math.BigDecimal has a stripTrailingZeros() method, which will achieve what you're looking for.
BigDecimal myDecimal = new BigDecimal(myValue);
myDecimal.stripTrailingZeros();
myValue = myDecimal.floatValue();
This handles it with two different formatters:
double d = 10.5F;
DecimalFormat formatter = new DecimalFormat("0");
DecimalFormat decimalFormatter = new DecimalFormat("0.0");
String s;
if (d % 1L > 0L) s = decimalFormatter.format(d);
else s = formatter.format(d);
System.out.println("s: " + s);
You just need to use format class like following:
new java.text.DecimalFormat("#.#").format(10.50000);
Format your numbers for your output as required. You cannot delete the internal "0" values.
Try using System.out.format
Heres a link which allows c style formatting
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
I had the same issue and find a workaround in the following link:
StackOverFlow - How to nicely format floating numbers to string without unnecessary decimal 0
The answer from JasonD was the one I followed. It's not locale-dependent which was good for my issue and didn't have any problem with long values.
Hope this help.
ADDING CONTENT FROM LINK ABOVE:
public static String fmt(double d) {
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
Produces:
232
0.18
1237875192
4.58
0
1.2345
I am using java big decimal as follwing:
class test bigDecimal{
private BigDecimal decimalResult;
public boolean iterate(String value) {
if (value == null) {
return true;
}
System.out.println("value is: " + value);
BigDecimal temp = new BigDecimal(value);
System.out.println("temp val is: " + temp);
if (decimalResult == null) {
decimalResult = temp;
} else {
decimalResult = decimalResult.add(temp);
}
return true;
}
}
all the strings that I am using to create big Decimal have scale of 6. For eg: 123456.678000, 456789.567890
But If I give a big list of strings as input and check the sum, I get output with 8 digits after decimal point. for eg. something like: 2939166.38847228.
I wonder why does BigDecimal change this scale ? all my input has scale of 6.
Any inputs are appreciated.
-thanks
Please read the javadoc for BigDecimal:
http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html
Internally all BigDecimals get converted to a some internal format.
If you want to get a specific format you have to call it appropriate.
You could use scaleByPowerOfTen(int n) with n=6 for example
Oh, and by the way never use new BigDecimal, use BigDecimal.valueOf instead.
EDIT:
NumberFormat numberFormat = NumberFormat.getInstance(); // use a locale here
String formated = df.format(myUnformatedBigDecimal);
It is not a problem of internal representation. This way the BigDecimal.toString() works. It calls layoutChars(true) - the private method that formats number. It has hard coded scale of 6. But I think it does not matter. You do not really have to pint all digits. BigDecimal provides ability to calculate high precision numbers. That's what it does.
Big decimal is giving an exact output, but that output is more accurate than 6 digits, so the best way to get 6 digit output is removing the last 2 decimals by converting the BigDecimal into string and doing something like that:
String myOutput = new
BigDecimal("1000.12345678").toString();
myOutput = myOutput.substring(myOutput.length-2,
myOutput.length);
I'd like to use Java's DecimalFormat to format doubles like so:
#1 - 100 -> $100
#2 - 100.5 -> $100.50
#3 - 100.41 -> $100.41
The best I can come up with so far is:
new DecimalFormat("'$'0.##");
But this doesn't work for case #2, and instead outputs "$100.5"
Edit:
A lot of these answers are only considering cases #2 and #3 and not realizing that their solution will cause #1 to format 100 as "$100.00" instead of just "$100".
Does it have to use DecimalFormat?
If not, it looks like the following should work:
String currencyString = NumberFormat.getCurrencyInstance().format(currencyNumber);
//Handle the weird exception of formatting whole dollar amounts with no decimal
currencyString = currencyString.replaceAll("\\.00", "");
Use NumberFormat:
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double doublePayment = 100.13;
String s = n.format(doublePayment);
System.out.println(s);
Also, don't use doubles to represent exact values. If you're using currency values in something like a Monte Carlo method (where the values aren't exact anyways), double is preferred.
See also: Write Java programs to calculate and format currency
Try
new DecimalFormat("'$'0.00");
Edit:
I Tried
DecimalFormat d = new DecimalFormat("'$'0.00");
System.out.println(d.format(100));
System.out.println(d.format(100.5));
System.out.println(d.format(100.41));
and got
$100.00
$100.50
$100.41
Try using
DecimalFormat.setMinimumFractionDigits(2);
DecimalFormat.setMaximumFractionDigits(2);
You can check "is number whole or not" and choose needed number format.
public class test {
public static void main(String[] args){
System.out.println(function(100d));
System.out.println(function(100.5d));
System.out.println(function(100.42d));
}
public static String function(Double doubleValue){
boolean isWholeNumber=(doubleValue == Math.round(doubleValue));
DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.GERMAN);
formatSymbols.setDecimalSeparator('.');
String pattern= isWholeNumber ? "#.##" : "#.00";
DecimalFormat df = new DecimalFormat(pattern, formatSymbols);
return df.format(doubleValue);
}
}
will give exactly what you want:
100
100.50
100.42
You can use the following format:
DecimalFormat dformat = new DecimalFormat("$#.##");
I know its too late. However following worked for me :
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.UK);
new DecimalFormat("\u00A4#######0.00",otherSymbols).format(totalSale);
\u00A4 : acts as a placeholder for currency symbol
#######0.00 : acts as a placeholder pattern for actual number with 2 decimal
places precision.
Hope this helps whoever reads this in future :)
You can try by using two different DecimalFormat objects based on the condition as follows:
double d=100;
double d2=100.5;
double d3=100.41;
DecimalFormat df=new DecimalFormat("'$'0.00");
if(d%1==0){ // this is to check a whole number
DecimalFormat df2=new DecimalFormat("'$'");
System.out.println(df2.format(d));
}
System.out.println(df.format(d2));
System.out.println(df.format(d3));
Output:-
$100
$100.50
$100.41
You could use the Java Money API to achieve this. (although this is not using DecialFormat)
long amountInCents = ...;
double amountInEuro = amountInCents / 100.00;
String customPattern;
if (minimumOrderValueInCents % 100 == 0) {
customPattern = "# ¤";
} else {
customPattern = "#.## ¤";
}
Money minDeliveryAmount = Money.of(amountInEuro, "EUR");
MonetaryAmountFormat formatter = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder.of(Locale.GERMANY)
.set(CurrencyStyle.SYMBOL)
.set("pattern", customPattern)
.build());
System.out.println(minDeliveryAmount);
printf also works.
Example:
double anyNumber = 100;
printf("The value is %4.2f ", anyNumber);
Output:
The value is 100.00
4.2 means force the number to have two digits after the decimal. The 4 controls how many digits to the right of the decimal.