How to convert decimal to whole number in java - 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

Related

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 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);

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

Java Decimal Format - as much precision as given

I'm working with DecimalFormat, I want to be able to read and write decimals with as much precision as given (I'm converting to BigDecimal).
Essentially, I want a DecimalFormat which enforces the following pattern "\d+(\.\d+)?" i.e. "at least one digit then, optionally, a decimal separator followed by at least one digit".
I'm struggling to be able to implement this using DecimalFormat, I've tried several patterns but they seem to enforced fixed number of digits.
I'm open to alternative ways of achieving this too.
Edit:
For a little more background, I'm parsing user-supplied data in which decimals could be formatted in any way, and possibly not in the locale format. I'm hoping to let them supply a decimal format string which I can use the parse the data.
Since you noted in a comment that you need Locale support:
Locale locale = //get this from somewhere else
DecimalFormat df = new DecimalFormat();
df.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));
df.setMaximumFractionDigits(Integer.MAX_VALUE);
df.setMinimumFractionDigits(1);
df.setParseBigDecimal(true);
And then parse.
This seems to work fine:
public static void main(String[] args) throws Exception{
DecimalFormat f = new DecimalFormat("0.#");
f.setParseBigDecimal(true);
f.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));// if required
System.out.println(f.parse("1.0")); // 1.0
System.out.println(f.parse("1")); // 1
System.out.println(f.parse("1.1")); // 1.1
System.out.println(f.parse("1.123")); // 1.123
System.out.println(f.parse("1.")); // 1
System.out.println(f.parse(".01")); // 0.01
}
Except for the last two that violate your "at least one digit" requirement. You may have to check that separately using a regex if it's really important.

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