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;
Related
I tried many ways to convert a Double to it's exact decimal String with String.format() and DecimalFormater and I found this so far :
String s = "-.0000000000000017763568394002505";
Double d = Double.parseDouble(s) * 100;
System.out.println((new java.text.DecimalFormat("###########################.################################################################################")).format(d));
(https://ideone.com/WG6zeC)
I'm not really a fan of my solution because it's ugly to me to make a huge pattern that does not covers all the cases.
Do you have another way to make this ?
I really want to have ALL the decimals, without scientific notation, without trailing zeros.
Thanks
P.S.: I need this without external libraries and in Java 1.7.
Seems as if you have to deal with some precision. double is not intended for this use. Better use BigDecimal
String value="13.23000";
BigDecimal bigD=new BigDecimal(value);
System.out.println(bigD);
System.out.println(bigD.stripTrailingZeros().toPlainString());
There is a big difference between new BigDecimal("0.1") and new BigDecimal(0.1). Using the String constructor can result in trailing zeros, and loses the effects of rounding to double on parsing the string. If the objective is to print the exact value of the double, you need to use BigDecimal's double constructor. Do any arithmetic in double, not BigDecimal.
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
String s = "-.0000000000000017763568394002505";
double d = Double.parseDouble(s) * 100;
System.out.println(new BigDecimal(d).toPlainString());
}
}
Try this code:
You can also use toString() method, but it uses scientific notation.
https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#toPlainString()
BigDecimal bd = new BigDecimal("-.0000000000000017763568394002505");
System.out.println(bd.toPlainString());
I have declared the variable for the double I'm using:
z= 345.876;
Now I want to display the number of digits that come before the decimal point. I tried to do the following:
String string_form = new Double(z).toString().subString(0,string_form.indexOf('.'));
double t = Double.valueOf(string_form);
I get an error saying: 'The method subString(int, int) is undefined for the type String'
Then a quick fix shows to change it small case s as: substring. However the error then changes to the string, 'string_form' which says it's not initialized. Any ideas on what to do?
And also how would I modify that to find the number of digits that come after a number? I know in the part
.indexOf('.')
I'd replace the decimal point with a number but how would i change it so that it displays how many digits come AFTER the number, not before? thanks. and yes I have imported the decimalformat text lang.
You're trying to use string_form before you have actually created it.
If you break
String string_form = new Double(z).toString().substring(0,string_form.indexOf('.'));
double t = Double.valueOf(string_form);
into
String string_temp = new Double(z).toString();
String string_form = string_temp.substring(0,string_temp.indexOf('.'));
double t = Double.valueOf(string_form);
Then it should work.
To get the numbers after the decimal point just take the digits from period until the end of the number.
String string_temp = new Double(z).toString();
String string_form = string_temp.substring(string_temp.indexOf('.'), string_temp.length());
double t = Double.valueOf(string_form);
As others have pointed out though, there are many better ways than converting to string and checking for period and reconverting.
The number of decimal digits before the decimal point is given by
(int)Math.log10(z)+1
The number of decimal digits after it is imprecise and depends on how much precision you use when converting to decimal. Floating-point values don't have decimal places, they have binary places, and the two are incommensurable.
just convert the double to a string. find the index of . with indexOf. get the length of the string. subtract the index of . from the length and you should have the count.
String string_form = Double(z).toString();
int index = string_form.indexOf('.');
double d = Double.parse(string_form.substring(0, index+1));
If the numbers are small, you could try
int i = (int) z;
or
long l = Math.round(z);
You're using string_form in the expression string_form.indexOf('.'), but it's not initialized yet, because it's only set after the call to substring(). You need to store the value of toString() in a temporary variable so you can access it in the call to substring(). Something like this
String stringForm = new Double(z).toString();
stringForm = stringForm.substring(stringForm.indexOf('.'));
There are other and better ways to do this, however. Math.floor(z) or even just a cast (long)z will work.
Could do this, for examble:
Integer.parseInt(String.valueOf(possibleBirths).split(".")[0]);
You can do the next thing:
Double z = 345.876;
int a = t.intValue();
int counter = 0;
while(a != 0) {
counter++;
a = a / 10; }
System.out.println(counter);
Sorry for the title name but this is probably a funny question. i need to have this like it is. I have an array of floats in the format [10.0, 20.0, 30.0, 40.0, 50.0] i need the array to be represented like [10.0f, 20.0f, 30.0f, 40.0f, 50.0f]. I have tried using array List to convert and add the notation and convert back.. but no matter what i try, i still get a float array that looks like a double. Any ideas Please?
even tried something like this:
ArrayList<String> valuelist = new ArrayList<String>();
for(int z = 0; z < mValues.length; z++){
valuelist.add(Float.toString(mValues[z]) + "f");
} //its fine here but later changes
Object[] objarray2 = valuelist.toArray();
String[] stringfloat = Arrays.copyOf(objarray2, objarray2.length, String[].class);
float[] myfloat = new float[stringfloat.length];
for(int j =0; j< myfloat.length; j++){
//myfloat[j] = Float.parseFloat(stringfloat[j]);
myfloat[j] = Float.valueOf(stringfloat[j]);
}
f is used to tell the compiler that treat this as float number. If you want your array in this format use an array of string and append f in each element
As per JLS:
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d (ยง4.2.3).
You have:
myfloat[j] = Float.valueOf(stringfloat[j]);
Here's Float.valueOf(String):
public static Float valueOf(String s) throws NumberFormatException
{
return new Float(FloatingDecimal.readJavaFormatString(s).floatValue())
}
As you can see, it returns a Float, which is created through Float(float) constructor, which is simply:
public Float(double value)
{
this.value = (float) value;
}
The readJavaFormatString(String) converts the String to a double, and .floatValue() converts the double, wrapped in a FloatingDecimal to a float, which is passed to the above constructor.
So, im short, you do have a float.
NB:
float num1 = XYZ;
float num2 = XYZf;
Despite the different notation, num1 and num2 compile to the same bytecode (where XYZ are some numbers, say 123); however, you cannot make an assignment of a number ending in an f to say an int. Additionally, if you try to put an int into a float, you do not need the f at the end, but if your number has any numbers to the right of the radix, you need to append the f so that it will compile with a possible loss of precision error.
Also, you really shouldn't be using float unless there's a good reason to do so, especially if you're planning to use == for comparison; instead, use double. float and double are essentially the same thing, except that double is 64-bits, whereas a float is 32-bits, so a double is more precise.
Keep the original array where members are float and just create a "String myToString()" method to print it like you want, with the +"f".
I mean, create a personalized method to print the array like you want it to appear.
I assume you just want the print out of the array of float to "appear" with a final f.
The representation in the machine of the number will not change with an f at the end or not.
The final f in the string is useful when parsing a number, so you the parser knows which kind of number it is, if you already do not tell it.
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.
Is there a way to execute a piece of code depending on how many decimal places there are in a number. For instance, if the double was just 2.0 i would want to convert it to an integer, but if it were 2.43426 i would want to leave it as a double. Thanks!
Not sure, but would:
double d = 2.0;
if ((long) d == d) {
// then
}
Work for you? That only answers your question in that particular case.
You can specify precision and convert like this:
double precision = 1e-10;
int rounded = Math.round(x);
if (Math.abs(x-rounded) > precision) System.out.print(x)
else System.out.print(rounded);
Convert the double to String
Using regex, find the decimal point and then get the number of characters after that.
Use it in your if-else
A quick and dirty solution would be the following:
double foo = 2.43426;
int count = String.valueOf(foo).split(".")[1].toCharArray().length;
if(count > 1){
// do stuff
}
If this is what you're after:
i would be converting them to strings and writing them out, so i would want it to say 3 instead of 3.0, but not 3 instead of 3.4324.
Then the "correct" way is using DecimalFormat:
DecimalFormat fmt = new DecimalFormat("0.#");
fmt.setMaximumFractionDigits(Integer.MAX_VALUE);
assert "3".equals(fmt.format(3.0));
assert "3.4324".equals(fmt.format(3.4324));
It does, however, localize the decimal separator (I get a comma rather than a dot). If that's an issue, you can just call fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ROOT)).