Convert Array to Floats Array with notation Java - java

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.

Related

I wont to get sum of Jtable column value (int + float) [duplicate]

The Java code is as follows:
String s = "0.01";
int i = Integer.parseInt(s);
However this is throwing a NumberFormatException... What could be going wrong?
String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;
The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense.
A double or a float datatype can hold rational numbers.
The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.
int i = (int) 0.9999;
i will be zero.
0.01 is not an integer (whole number), so you of course can't parse it as one. Use Double.parseDouble or Float.parseFloat instead.
Use,
String s="0.01";
int i= new Double(s).intValue();
String s="0.01";
int i = Double.valueOf(s).intValue();
This kind of conversion is actually suprisingly unintuitive in Java
Take for example a following string : "100.00"
C : a simple standard library function at least since 1971 (Where did the name `atoi` come from?)
int i = atoi(decimalstring);
Java : mandatory passage by Double (or Float) parse, followed by a cast
int i = (int)Double.parseDouble(decimalstring);
Java sure has some oddities up it's sleeve
Using BigDecimal to get rounding:
String s1="0.01";
int i1 = new BigDecimal(s1).setScale(0, RoundingMode.HALF_UP).intValueExact();
String s2="0.5";
int i2 = new BigDecimal(s2).setScale(0, RoundingMode.HALF_UP).intValueExact();
suppose we take a integer in string.
String s="100";
int i=Integer.parseInt(s);
or
int i=Integer.valueOf(s);
but in your question the number you are trying to do the change is the whole number
String s="10.00";
double d=Double.parseDouble(s);
int i=(int)d;
This way you get the answer of the value which you are trying to get it.
use this one
int number = (int) Double.parseDouble(s);
Use Double.parseDouble(String a) what you are looking for is not an integer as it is not a whole number.
One more solution is possible.
int number = Integer.parseInt(new DecimalFormat("#").format(decimalNumber))
Example:
Integer.parseInt(new DecimalFormat("#").format(Double.parseDouble("010.021")))
Output
10

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 tell if a result is decimal?

I'm having two float numbers, they can be decimals or not, depending on the operation I want to print the result either with decimal or without.
I'm using String.format to take off the decimal when not needed. However, I have trouble identifying when the result will be decimal. Tried the n1 % n2 > 0 method from a similar question, but when entering for example 6 + 7 the result becomes 13.0 instead of just 13.
Code so far:
float n1 = Float.parseFloat(request.getParameter("num1").toString().trim());
float n2 = Float.parseFloat(request.getParameter("num2").toString().trim());
String res = String.valueOf(n1+n2);
if(n1 % n2 > 0)
{
out.println("It's decimal");
out.println(n1+n2);
}else{
out.println(String.format("%.0f", n1+n2));
}
For doing exact math with non-integers (numbers with fractions) in Java you should use BigDecimal. This class allows for exact representation of non-integers of arbitrary precision.
That is your code should be changed to:
final BigDecimal n1 = new BigDecimal(request.getParameter("num1").toString().trim());
final BigDecimal n2 = new BigDecimal(request.getParameter("num2").toString().trim());
final BigDecimal res = n1.add(n2);
final BigDecimal remainder = n1.remainder(n2);
//if (res.stripTrailingZeros().scale() > 0) {
if (remainder.compareTo(BigDecimal.ZERO) != 0) {
System.out.println("It's decimal");
System.out.println(res);
} else {
final DecimalFormat df = new DecimalFormat("#.0f");
System.out.println(df.format(res));
}
The other answer will not give you the correct result, if a user inputs a number larger than Integer.MAX_VALUE or lower than Integer.MIN_VALUE. Casting to long will probably yield wrong results due to the precision of float that might cause the result to have a decimal fraction even if the input numbers did not...
However I hope you're doing some input validation of the request data. Otherwise you'll most likely get a lot of NumberFormatExceptions from your JSP-page.
UPDATE:
Updated the code example to check for scale instead of precision.
You can use Math.round to tell if a float is an integer. (There are other approaches if your only purpose is to suppress the decimal point for integers when formatting as a string--see KevinO's comment.)
If f is a float, Math.round(f) returns an int, which is f rounded to the nearest integer, unless f is outside the range of an int. However, if f is outside the range of an int, then f must be an integer, for all practical purposes--if f is large enough that it is too big to fit in an int, then it's too big to distinguish between values that are less than 1.0 apart (there are fewer bits of precision in a float than in an int). So there's no way for f to represent a non-integer of that magnitude.
Given that, and assuming that f isn't +/- infinity, you can test whether f is an integer like this:
public boolean isInteger(float f) {
return f > (float)Integer.MAX_VALUE ||
f < (float)Integer.MIN_VALUE ||
f == (float)Math.round(f);
}
But please note that even a non-integer could appear as something.000000 when you format it, since the formatter will have to round f to a certain number of decimal places when printing. It depends on what kind of format you're using.
NOTE: The above method is a correct way to determine whether a float is an integer, if the float is the only information you have. However, in the context of a larger program, there are other considerations. If the parameter string is "2000000000.1", when you parse it as a float you will get 2000000000, which is an integer, because the float doesn't have enough precision to represent the .1. At that point, your float will be an integer value, and it's too late for it to know about the .1--that information has been lost. If you don't want to lose that information, then don't use float or double--use BigDecimal instead.
Cast to int then back:
boolean isDecimal = myFloat != (float)(int)myFloat;
Casting to int truncates the decimal part.
Or, you can use a string approach. Decimals have non-zero digits after the dot, so:
boolean isDecimal = String.valueOf(myFloat).matches(".*\\.(?=.*[1-9]).*");
If you just need that for output, the easiest approach is probably to do this with string manipulation:
String s = String.format("%.4f", n1 + n2); // use whatever decimal places you like
s = s.replaceFirst("\\.0*$", "");
System.out.println(s);
This will fail if the decimal separator in your Locale is , instead of ., so be careful.
To really check if a double value x is integral you can use this test:
if (x % 1 == 0) {
// integral
} else {
// not integral
}

Finding number of digits before a decimal point in java

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

Compare float values entered by users (Android)

I have some problem with precised comparison of float values entered by users into an editable text field in my app. Here is example:
if ((temp>=39.0)&&(temp<=40.9)) {
ball=ball+3;
}
If user enters, for example, 40.9, the code in the loop isn't called. I am just a beginner, any help appreciated.
You should represent your literal values as 40.9f. If you omit the 'f' the type of the literal will default to double. Also check what the type is of your temp variable. You didnt show how you declare temp.
EDIT
If you declared temp as a Float or a float, and 40.9 is a double, your expression (temp <= 40.9) is comparing a float to a double, so the compiler will automatically cast the double to a float. Converting a double to a float means halving the number of bytes of the variable, so the resulting float may be very different from the expected value.
Try to create a very small margin:
float epsilon = 0.0001f;
if (39.0f - epsilon <= temp && temp <= 40.9f + epsilon)
{
}
And make sure you are parsing the user input correctly.
float temp = Float.parseFloat(inputField.getText());

Categories

Resources