How to remove scientific notation from double for longest double value - java

I am experiencing a problem in Double value manipulation.
Lets take,
Double d = new Double(123456789987654321123456789d);
System.out.println(d);
The output is :
1.2345678912345678E35
But I want,
123456789987654321123456789
The complete digit without any notation.
I have tried all permutation using BigDecimal, BigInteger and so and so.
Note: I want to populate into JSON so please don't suggest just a print statement.
I have already read :
How to Avoid Scientific Notation in Double?
Formatting a double and not rounding off

Try this BigDecimal::toPlainString:
BigDecimal d = new BigDecimal("123456789987654321123456789");
String result = d.toPlainString();
Output of d is :
123456789987654321123456789
To populated to JSon there are many ways, I'm not sure what you want exactly, but maybe this can help you How to create JSON Object using String?:
BigDecimal d = new BigDecimal("123456789987654321123456789");
JSONObject myObject = new JSONObject();
myObject.put("number", d.toPlainString());

You can try this
String str = String.format("%.0f", d);
Note that max digits a double can hold is ~17, so 123456789987654321123456789 will rounded

Related

How to remove decimal in java without removing the remaining digits

Is there any method to remove the . in java into a double value?
Example :
56.11124
to
5611124
I don't think there's a mathematical way to find out how many decimals there are in a double. You can convert to a String, replace the dot, and then convert it back:
Double.parseDouble(Double.toString(56.11124).replace(".", ""));
Be careful of overflows when you parse the result though!
Here's one way to do it,
First, convert the double to a string. Then, call replace to replace . with an empty string. After that, parse the result into an int:
double d = 5.1;
String doubleString = Double.toString(5.1);
String removedDot = doubleString.replace(".", "");
int result = Integer.parseInt(removedDot);
Obviously, this wouldn't work if the double's string representation is in scientific notation like 5e16. This also does not work on integral double values, like 5, as its string representation is 5.0.
doubles are inaccurate by nature. 5 and 5.0 are the same value. This is why you can't really do this kind of operation. Do you expect different results for a and b?
double a = 5;
double b = 5.0;
If you do, then you can't really do this, since there is no way of knowing what the programmer wrote exactly at runtime.
This might work
class Example {
public static void main(String[] args) {
double val = 56.1112;
while( (double)((int)val) != val )
{
val *= 10;
}
System.out.printf( "%.0f", val );
}
}
Output: 561112
This works by casting the double to int which truncates the floating information 56.11124 => 56. While the values aren't equal you multiply it by the base to push the . out. I don't know if this is the best way.
You can convert to BigDecimal and use the unscaledValue method:
BigInteger unscaled = new BigDecimal(myDouble).unscaledValue();
Depending on your intended output, you might also use BigDecimal#valueof(double) to create the intermediate BigDecimal.
Javadoc for BigDecimal#new(double)
Javadoc for BigDecimal#valueOf(double)
Javadoc for BigDecimal#unscaledValue()
You can convert it to a String and remove the . and convert it back to double something like
double value = 56.11124;
value = Double.valueOf(("" + value).replace(".", "")).doubleValue();
This will return 5611124.0 since its a double you will have the floating point. You can convert it to an int, but you have to take care of the possible overflow. Otherwise it would look like this
int normalized = (int) value;

how to print precise floating double values

i want to print a double value like 0.000027,
but it's getting printed as 2.7340E-05.
i'm using-
editTextYARD.setText(String.format(Locale.US, "%6.4E"));
please help...
This will convert a given double value to show decimal point up to 7
double value = 0.0000027;
System.out.println(String.format("%.7f", (double)value));
you may use it like this
editTextYARD.setText(""+String.format("%.7f", (double)value));
You can use DecimalFormat for this purpose.
double myvalue = 1.2345678878;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(10);
your_editText.setText(df.format(myvalue));
When print to console:
System.out.printf( "%04.2f", var)
When print to string, I think ( I am not tried yet...)
This worth trying..
String ret = String.format ("%04.2f", var)

Conversion of BigDecimal to double

While converting BigDecimal to double, extra precisions are getting added.
Could you please suggest this.
For Ex:
BigDecimal deci= new BigDecimal(1.23456789123457E+17);
double value = deci.doubleValue();
System.out.println(value);
And value prints - 1.23456789123456992E17. How come the last digit 7 is converted to 6992? Is there is any way I can get the same input which I am passing to BigDecimal after converting to double?
There are useful methods Math.nextUp() and Math.nextDown() which can help you to investigate this issue:
BigDecimal deci= new BigDecimal(1.23456789123457E+17);
double value = deci.doubleValue();
System.out.println(value);
System.out.println(Math.nextDown(value));
System.out.println(Math.nextUp(value));
The output is:
1.23456789123456992E17
1.23456789123456976E17
1.23456789123457008E17
So as you can see, the double number ...456976 is immediately followed by ...456992, which in turn is immediately followed by ...457008. So BigDecimal.doubleValue() should select between two closest numbers ...456992 and ...457008. No other double number exist between them.
Actually you don't even need the BigDecimal for this test:
double value = 1.23456789123457E+17;
System.out.println(value); // prints 1.23456789123456992E17

Move decimal point in double

I have this code:
Long dval = new Long((new Date()).getTime());
System.out.println("ogval:"+dval);
Double dd = (double)dval;
System.out.println("dval:"+dd);
Here is the output:
ogval:1381490769636
dval:1.381490769636E12
When I convert the value to Double, it adds a decimal point. Can I do the typecasting and get the value in double as it is?
The desired output would be:
ogval:1381490769636
dval:1381490769636
I have a function whose argument accepts only double value. When I try to pass a timestamp, it passes the decimal value inside the method.
I can't edit the function because its an inbuilt function of some package.
Simple answer is no.
Floating types can contain integer up to some arbitrary value, given by the way floats are stored. If the number is too big, it gets converted to decimal.
If you need to work with big integer values use BigInteger class.
Great tool to examine those imperfections is this float converter.
Try 123456789 in the float converter, it won't be stored exactly.
Use DecimalFormat, like:
Long dval = new Long((new Date()).getTime());
System.out.println("ogval:" + dval);
Double dd = (double) dval;
DecimalFormat format=new DecimalFormat("##########");
System.out.println("dval:" + format.format(dd));
Your problem is not with the type that you are using, but with the format that you are applying to it. Currently, the default format is used, because string + double implicitly calls Double.toString, which converts your specific double to a String using scientific notation. You can force a different format if you wish by using printf or any other formatting method that Java makes available to you:
System.out.printf("dval: %12.0f", dd);
(demo)
as an alternative you can try using bigdecimal
Long dval = new Long((new Date()).getTime());
System.out.println("ogval:"+dval);
Double dd = (double)dval;
System.out.println("dval:"+dd);
BigDecimal bd = new BigDecimal(dval);
System.out.println("bdval:"+bd.toPlainString());

Java convert string to number, floating point only when needed?

I want to conver a string to number in Java. I already tried with two methods but both work bad with integers, adding an unneeded floating point: "1" > 1.0 (when I want "1" > 1 and "1.5" > 1.5). I found a couple more ways to convert strings to numbers but they either don't work or are many lines long, I cannot believe it's so complicated coming from javascript where I only need parseFloat().
This is what I'm trying now:
String numString = "1".trim().replaceAll(",","");
float num = (Float.valueOf(numString)).floatValue(); // First try
Double num2 = Double.parseDouble(numString); // Second try
System.out.println(num + " - " + num2); // returns 1.0 - 1.0
How can I have the floating point only when needed?
To format a float as you wish, use DecimalFormat :
DecimalFormat df = new DecimalFormat("#.###");
System.out.println(df.format(1.0f)); // prints 1
System.out.println(df.format(1.5f)); // prints 1.5
In your case, you could use
System.out.println(df.format(num) + " - " + df.format(num2));
I think what you're looking for is DecimalFormat
DecimalFormat format = new DecimalFormat("#.##");
double doubleFromTextField = Double.parseDouble(myField.getText());
System.out.println(format.format(doubleFromTextField));
The problem is with your question really in a type-safe language and I think you are mixing conversion and string representation. In Java or C# or C++ you convert to some predictable/expected type, looks like you expect the "Variant" behavior that you are used to in JavaScript.
What you could do in a type-safe language is this:
public static Object convert(String val)
{
// try to convert to int and if u could then return Integer
ELSE
//try to convert to float and if you could then return it
ELSE
//try to convert to double
etc...
}
Of course this is very inefficient just like JavaScript is compared to C++ or Java. Variants/polymorphism (using Object) comes at cost
Then you could do toString() to get integer formatted as integer, float as float and double as double polymorphically. But your question is ambiguous at best that leads me to believe that there is conceptual problem.

Categories

Resources