i want to let users edit a field with double data. I want to allow Double.NaN (to void values). Is there a generic way (a predefined string) that is parsed to Double.NaN from the method Double.valueOf(String) without checking it in the background?
There is a special char looking like a diamond with a question mark in it (in HTML) that acts like NaN, but - well - the users wont find that on their keys.
You can pass +NaN or -NaN or NaN to valueOf() and have it return a NaN. The documentation gives the full details.
parseDouble("NaN") will return a NaN value:
System.out.println(Double.isNaN(Double.parseDouble("NaN"));
Related
I used to initialize double variables with Double.NaN and fill them later depending on the input. If there were mistakes in inputs I just return Double.NaN. This practice backfired, when other part of application used my function as input and worked just OK, doing basic arithmetic and comparing NaNs with double (but didn't supposed to, I would expect exception).
The obvious solution would be to add Double.isNaN() at the end of my code and throw exception inside my function
But this is a highly used function in highly optimized code, so I'm unwilling to add extra check each time it is called. I would rather prefer break the whole application on wrong parameters once a year than add an extra check, esp. I heard that comparing to NaN takes longer than comparing to double. How do I achieve that and what are best practices in this situation?
EDIT
for example, I want to return first parameter for parametric function which I know nothing about depending on user input
private double getFirstFactor(HashMap <String, Double> userParams) {
double res = Double.NaN;
if(userParams.containsKey("factor1")) {
res = userParams.get("factor1");
}
return res;
}
Usage
double f1 = getFirstFactor(userParams);
double threshold = f(f1); // for example f1 * 100 + f1;
// ideally, code above breaks if f1 is not defined and I don't go futher
if(threshold >= 0) {
...
} else {
...
}
Don't do that.
NaN is used for the result of certain expressions (e.g. 0.0 / 0.0) and has the unique property that it compares false with itself.
You should always initialise double values with something sensible. Depending on your algorithm, 0.0 and 1.0 are often good values.
If you really can't do that then you could always use a Double, with null as your default-initialised value.
You should always validate your inputs before using them. If your inputs are invalid, you can throw an IllegalArgumentException before any computation is done at all. It makes it the caller's responsibility to use your code with correct inputs.
It's always better to fail fast, instead propagating invalid values throughout your system. This can cause big problems (as you probably have experienced).
Use boxed type Double and use null as default value insteed of Double.NaN. If I would need to stick to primitives, I would got for 0.0d as default value.
I am trying to program (in Java) what seems like a relatively easy set of requirements but I am having trouble with types. I want to take scientific data from an instrument and put it through some logic to come up with an answer. My problem is that the data will either come off as a string (always "None") or a double. The data set will be two points per sample. So, here are my thoughts: I need class with two parameters that can be either a string or double. So, I decided I would make a class with generic parameters. When it came to performing the logic on the double or string, I had trouble. For example, here are two parts of the logic:
If v < 26 and f is between 36.5 and 37, then sample needs to be rerun.
If v > 31 and f is "None", then rerun.
There are more rules but I won't include them all here, but both v and f may be either a double or "None".
If all the values were doubles I would have no problem, but the fact that I can get doubles or strings is giving me trouble when trying to compare the two. I'm not sure if a generic class is the way to go. Any ideas?
Also, this is my first post so please let me know if you need more information or have any tips on posting.
Thanks!
You are mistaken: Your input type is always String (if it can be "None" it is a String). However, it can be a String with numbers and a dot that may be parsed as a Double.
Something like this should help:
public static Double parseInput(String input) {
try {
return input.equals("None") ? null : Double.valueOf(input);
} catch (NumberFormatException | NullPointerException e) {
return Double.NaN;
}
}
This returns a null for "None", which seems the most reasonable mapping, and handles anything not a number (blank, null, bad data) by returning the special "not a number" Double value.
I suggest you to use String as parameter type, then inside your class you can try to parse the value to double and apply your logic on it if the value can be parsed to double.
If not, then the value is a String and you have to apply the logic of String values
If all the values were doubles I would have no problem,
Similar to #Bohemian's answer but I would make use of NaN and leave the value a primitive.
public static double parseInput(String input) {
return "None".equalsIgnoreCase(input)
? Double.NaN
: Double.parseDouble(input);
}
To check for none use
If v > 31 and f is "None", then rerun.
if (v > 31 && Double.isNaN(f))
This question already has answers here:
Which is better/more efficient: check for bad values or catch Exceptions in Java
(11 answers)
Closed 9 years ago.
I have seen two styles for checking whether a variable is a valid integer in Java. One by doing an Integer.parseInt and catching any resulting exception. Another one is by using Pattern.
Which of the following is better approach?
String countStr;
int count;
try {
count = Integer.parseInt(countStr);
} catch (Exception e) {
//return as the variable is not a proper integer.
return;
}
or
String integerRegex = "([0-9]{0,9})";
if (countStr.isEmpty() || !Pattern.matches(integerRegex, countStr)) {
//return as the variable is not a proper integer.
return;
}
My question here is, is doing an Integer.parseInt() and catching an exception for validation a standard way to validate an int? I admit that my regex is not perfect. But is there any built-in methods available in Java for validation of int? Actually isn't it better to do some validation instead of simply catching the exception?
Using the approach above is better as it considers all types of possible errors and handles all cases. For instance what you have written will not parse negative numbers correctly.
It only makes sense to write your own verifier if you want to validate a given subset of all integers.
A general advice: don't re-invent the wheel unless you have strong reasons to do so.
There's a really good reason to not go with the second approach if you actually want to check if the given string can be represented as a 32bit integer and not just that it represents an integer in the mathematical sense.
I'm sure we all agree that 2147483648 (2**31 for those paying attention) is a perfectly fine integer, but it's only one of infinitely many numbers for which the two options will give different results. So if you want to check if you can represent a string as a 32bit integer use the parseInt method, if you just want to see if it's an integer go with the regex.
PS: That said don't catch Exception, but the correct NumberFormat exception instead..
These two function serve different purposes. If you just want to make sure that the string cotains a particular pattern, then use the second approach. If you need to convert it, then you should can parseInt() In this case it wouldn't make sense to check it and convert it as well.
However, if you have specific requirements for the number, then you may have to check it first regardless, because parseInt() may not always throw an exception if it can parse something which still doesn't fit your requirement.
If you just validat an Integer, I think the second way is better.
These two methods both will work fine, but obviously different focus. The former focuses on the transformation itself, while the latter is clearly more attention checked. And you want to check a number is, so I think the second method is better. Also, I think, some of the second method more readable, allowing code maintenance is a clear to see, where the logic is in checking the validity of a number instead of a string into a number.
I sometimes tend to use (double)(long)(a*b/c) to store the integer part of the result as double. This works well for negative numbers too.
Is there any better way to achieve the same thing as I believe typecasting is a costly operation.
Please note I'm looking for Integer part of the number and not the rounded value.
For eg :
MyObj.setDouble((double)(long)(522.99))
MyObj.getDouble() returns 522.0 and not 523.0
Thanks.
Try Math.rint(double) or Math.round(double). Regardless of performance differences it's at least more clear and concise.
[Edit]
In response to your clarified question - "how do I get the integer part of a double without casting" (despite your title asking about rounding), try this:
public static double integerPart(double d) {
return (d <= 0) ? Math.ceil(d) : Math.floor(d);
}
integerPart(522.99); // => 522d
integerPart(-3.19); // => -3d
Of course, this form is likely no faster than casting since it's using a comparison and a method call.
Performance is not an issue here. But code (double)(long)(a*b/c) is ugly. You actually do not need casting at all if you assign the result to `double variable:
double d = a*b/c; exactly the same as double d = (double)(long)a*b/c;
You actually never need to perform casting when moving from lower to upper types. It is correct for primitives (e.g. int -> double) and for classes (e.g. ArrayList -> List).
What about Math.floor(double) I cant see the difference between integer part and rouding it down.
I just bumped into this little problem and I wanted the input of other people on this
I was wandering what was the best solution to convert a String to an int
(int)(float)Float.valueOf(s)
or
Float.valueOf(s).toInt()
s is a String inputed from a textfield so I can not guarantee that it is necessarily an int
my instincts is that the double cast is ugly and should be avoided
Your input?
Your requirements are unclear:
If you are expecting an integer and don't want to allow the user to enter a number with a decimal point in it, simply use Integer.valueOf(String) or Integer.parseInt(String) and catch the NumberFormatException.
If you want to allow numbers with decimal points, then use Float.valueOf(String) or Float.parseFloat(String).
If you simply want to truncate the float to an int then either Float.intValue() or two casts are equivalent. (The javadoc for intValue explicitly states this.)
If you want to round to the nearest int, use Math.round() instead of a cast.
You should catch NumberFormatException whatever approach you take, since the user could enter rubbish that is not a valid base-10 number (with or without a decimal point) ... or that exceeds the bounds of the number type.
(I suppose that you could use a regex or something to check the String before trying to convert it, but it is simpler to just let the exception happen and deal with it. The exception efficiency issue is unlikely to be a practical concern in this use-case.)
On your original question as to whether intValue() is better than two casts: it is a matter of style. The two approaches do the same thing ... according to the javadoc. It is possible that one will be slightly more efficient than the other, but:
that shouldn't be a concern for your use-case, and
the only way to know for sure would be to profile the two alternatives on your execution platform ... and frankly it is not worth the effort.
You should use Integer.valueOf(..), and catch the NumberFormatException (if the string cannot be parsed as an integer).
Integer.parseInt(string) would be best
int x = Integer.parseInt(s);
Would be best to check if the string is an int before calling this.
As others pointed out, its just matter of style not performance... but if you are worried about performance you should validate the text field data in browser itself by javascript using a regex
^[0-9]*$
which would allow only integers to be submitted to your back-end code and hence improving performance by avoiding one network trip. Still you should validate the data in back-end, for that you can use
Integer.parseInt(String s) throws NumberFormatException