Retain formatting of a Double value - Java - 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

How to convert decimal to whole number in java

Hi i have an output as "1.234567E6" and similar. Now i want my output to be converted to 1234567. Could you please suggest how to acheive this? Splitting is one way but then E6 part handling i am not sure.
Also the output will be varying in nature, sometimes it would be 6 decimal places , sometimes 10
You can use Double.valueOf then get the long value
long val = Double.valueOf("1.234567E6").longValue();
Or use BigDecimal with longValueExact() to avoid rounding error
long val = new BigDecimal("1.234567E10").longValueExact();
Note: longValueExact() throws Arithmetic Exception if there is any fractional part of this BigDecimal.
You can check the demo here
Use DecimalFormat, it's consistent and clear approach:
DecimalFormat decimalFormat = new DecimalFormat("0");
System.out.println( decimalFormat.format( 1.234567E6 ) );
In String case:
System.out.println( decimalFormat.format( Double.parseDouble("1.234567E6") ) );
Output in both cases
1234567
See code in action: http://tpcg.io/9DsB3GRH

In Java, how do you print out an anwer in a different literal?

I know that you add an L to a value if it exceeds the scope of an integer but you still have to print it as such. I understand the concept of doing it when you're just printing out a plain number.
What about when you're using a defined variable instad?
Say I have something like.
double a = 2.5;
System.out.println(a);
I want "a" to be printed out as a integer.
Thanks for any answers in advance :)
You can use Math.round for instance.
System.out.println(Math.round(a));
or you can format it as an integer as follows:
System.out.printf("%.0f%n", a);
cast double a to Double and use a.intValue()
Double a = new Double("2.5");
System.out.println(a.intValue());
You could use a NumberFormat. There are predefined formats available which you could use for your particular use-case.
NumberFormat format = NumberFormat.getIntegerInstance();
double a = 2.5;
System.out.println( format.format( a ) );
But it also allows to create one for more difficult output, like with a specified number of decimals. That would be much harder using Math.round or the other suggestions made here.

How to keep n decimal places in Java

Hi All it might be a trivial question but as for now I could not find any solution.So asking for your help!
What I am trying to get is a specific encoding table that looks like this:
0.000
0.100
0.200
I need to keep track of zeroes as I will use them to reconstruct a part of an specific array. Original loop that was creating those numbers is:
for(int k=0;k<m_0;k++){
for(int l=0;l<m_1;l++){
for(int a=0;a<a1;a++){
Y[x-1]=0.1*k+0.01*l+0.001*a;
x++;
}
}
}
Problem! I could not fix zeros after decimal place and rather then getting table described above I am getting following:
0.0
0.1
0.2
As a solution I have tried to use BigDecimal and DecimalFormat but no success. Any suggestions?
UPD Few words what I am trying to do. I am encoding specific array to array and back index correspondence. For example 0.100 will be decomposed into 1 and 0 and 0 and used as array index labeling like:
Array1[Method(1,0,0,Y(i)][Method(1,0,0,Y(i))]=Array2[1][0][0]
So that I need an output suitable for assigning array index and string will not do the deal.
The DecimalFormat class is the correct place to look. You just need the correct format.
DecimalFormat df = new DecimalFormat("0.000");
System.out.println(df.format(0.1));
Output:
0.100
As an alternative to the DecimalFormat class, I would like to propose the following (which I use quite regularly):
Step 1: Create a function that allows me to specify the number of units to keep. Here is a copy of this function.
public static String format(Number n) {
NumberFormat format = DecimalFormat.getInstance();
format.setRoundingMode(RoundingMode.FLOOR);
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(2);
return format.format(n);
}
Step 2: Call the function whenever you have any output to format. Below is a simple example using this function to set the appropriate decimal place length:
System.out.println("Based on this, the wind chill index was calculated to be " + format(chill));
Note that you could simply change the line:
format.setMaximumFractionDigits(2);
to
format.setMaximumFractionDigits(n);
depending on your desired decimal length.
When you are printing the numbers, you can use this:
System.out.format("%.3f", yourDecimalNumber);

How to format numbers on Android

i am learning to program mobile aplications on Android. My first app is a unit converter. Everithing is working for now, but i have a question about formating numbers. I hava this code to get text from buttons and to convert the appropriet output:
if (bPrevodZ.getText() == "milimeter"){
if (bPrevodDo.getText()=="kilometer"){
String PomocnaPremenna = jednotkaZ.getText().toString();
double cisloNaPrevod = Double.parseDouble(PomocnaPremenna);
cisloNaPrevod = cisloNaPrevod*0.0000001;
vysledok.setText(Double.toString(cisloNaPrevod));
}
The final result is "cisloNaPrevod", but i have problems to show a good format of that number. For example:
12345 mm = 0,0012345 km this is good right ? :)
but if i convert:
563287 mm = 0.05632869999999995 this is bad :) i need it to show 0.0563287
Thx for any help
Use String.format:
String.format("%.6f", cisloNaPrevod);
If you want your number to always have 6 significant figures, use
vysledok.setText(String.format("%.6g", cisloNaPrevod));
giving the result 0.0563287.
If you want to round to 6 numbers after the decimal place, use
vysledok.setText(String.format("%.6f", cisloNaPrevod));
giving the result 0.056329.
Here's some good resources that cover number formatting:
Floating-point cheat sheet for Java
java.util.Formatter
If it's something you're going to do often, perhaps you should use DecimalFormat.
DecimalFormat df = new DecimalFormat("#.#######");
Then call:
df.format(someDoubleValue);

Formatting a Double into the correct format

Having problem getting a Longitude/Latitude into the correct format for an api we don't have access to.
We need to convert this to a string and at the moment we have: 4.30044549E7
as the raw form but we need to convert it into 4.30044549 or similar (without Scientific Notation)
If we use
NumberFormat f = new DecimalFormat("#.#######");
f.format(4.30044549E7);
we get: 43004454.9
if we use
Double.toString(4.30044549E7);
we get: "4.30044549E7"
if we try to convert to an int we also get 43004454.9
Can anyone help? I can't find an acceptable solution to get rid of scientific notation on the number
If you really asked what I think you did, you could simply divide the number by 10 until you reach the format you wanted.
double value = 4.30044549E7;
while(value > 10 || value < -10){
value /= 10;
}
System.out.println(String.format("%.8f", value)); //4.30044549
Have you tried format?
String.format("%.10f",doubleValue);
It will format your number with 10 digits after dot.
1e-5 -> 0.000010000
1e5 -> 100000.0000000000
you never can "format" 4.30044549E7 into 4.30044549 because they are not the same.
4.30044549E7 is in fact 43004454.9 so wanting a formatter to display that double as 4.30044549 is an odd question

Categories

Resources