I'm parsing a file that has integer values using commas to separate thousands.
String s = "1,503"
Integer i = new Integer(s)
does not work, throws a parse exception. Is there an easy way to parse this?
Thanks
A slightly more groovy method might be;
int a = java.text.NumberFormat.instance.parse( '1,234' )
But this will use the default locale
Use NumberFormat instead. For example, in Java:
import java.util.*;
import java.text.*;
public class Test {
public static void main(String args[]) throws ParseException {
NumberFormat format = NumberFormat.getIntegerInstance(Locale.US);
Long parsed = (Long) format.parse("1,234");
System.out.println(parsed);
}
}
(You can then get the integer value from the Long, of course.)
I've explicitly specified Locale.US to guarantee that comma is used as the thousands separator; you may want to use a different locale if the input can vary.
Related
i'm new to kotlin android studio,trying to update the textView with editText from data class and i used in editText "afterTextChanged" , created a setter function in data class with editable paramete, i can't convert double to string with editable, anyone help me out ?
here is function in data class
fun setSize(editable: Editable) {size = editable.toString()}
Your size variable is (apparently) a Double, so you have to assign a Double value to it. You're doing editable.toString() which just gives you a String representation of your Editable's contents.
You need to try and parse that as a Double with toDouble() (which throws an exception if it's not a valid number) or toDoubleOrNull (which returns null if it's invalid).
Since it's (I assume) user-edited content you're parsing, and there's a good possibility they'll enter something that's not a valid number representation, you need to handle that possibility. I'd go with toDoubleOrNull since it's easier in Kotlin (there are lots of these *OrNull variants on functions for that reason):
fun setSize(editable: Editable) {
// only runs the let block if the value is parsed
editable.toString().toDoubleOrNull()?.let { size = it }
}
or if you're not familiar with let:
fun setSize(editable: Editable) {
val double = editable.toString().toDoubleOrNull()
if (double != null) size = double
}
I'm using JSF 2.
I have a method that checks for matching values from a list of values:
#ManagedBean(name="webUtilMB")
#ApplicationScoped
public class WebUtilManagedBean implements Serializable{ ...
public static boolean isValueIn(Integer value, Integer ... options){
if(value != null){
for(Integer option: options){
if(option.equals(value)){
return true;
}
}
}
return false;
}
...
}
To call this method in EL I tried:
#{webUtilMB.isValueIn(OtherBean.category.id, 2,3,5)}
But it gave me a:
SEVERE [javax.enterprise.resource.webcontainer.jsf.context] (http-localhost/127.0.0.1:8080-5) java.lang.IllegalArgumentException: wrong number of arguments
Is there a way to execute such a method from EL?
No, it is not possible to use variable arguments in EL method expressions, let alone EL functions.
Your best bet is to create multiple different named methods with a different amount of fixed arguments.
public static boolean isValueIn2(Integer value, Integer option1, Integer option2) {}
public static boolean isValueIn3(Integer value, Integer option1, Integer option2, Integer option3) {}
public static boolean isValueIn4(Integer value, Integer option1, Integer option2, Integer option3, Integer option4) {}
// ...
As a dubious alternative, you could pass a commaseparated string and split it inside the method
#{webUtilMB.isValueIn(OtherBean.category.id, '2,3,5')}
or even a string array which is created by fn:split() on a commaseparated string
#{webUtilMB.isValueIn(OtherBean.category.id, fn:split('2,3,5', ','))}
but either way, you'd still need to parse them as integer, or to convert the passed-in integer to string.
In case you're already on EL 3.0, you could also use the new EL 3.0 collection syntax without the need for the whole EL function.
#{[2,3,5].contains(OtherBean.category.id)}
I want to convert my string value to int16 and only show 2 decimal places. I have tried the below, but it throws an error as my string value is not actually converted?
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string number1 = "1234.00011";
Console.Write(number1);
Console.WriteLine();
string r = String.Format("{0:F2}", number1);
Console.Write(Convert.ToInt16(r));
}
}
}
EDIT
The line that throws the error is
Console.Write(Convert.ToInt16(r));
And the error is
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
Your call to string.Format is using a floating point format specifier and providing a string argument. These are mutually incompatible. As a result, the string argument is inserted as-is into the result, and stored in r, so that you don't get the desired two-digit rounding you're looking for.
What you likely want to do is something like this:
static void Main(string[] args)
{
string number1 = "1234.00011";
Console.Write(number1);
Console.WriteLine();
var r1 = float.Parse(number1);
string r = String.Format("{0:F2}", r1);
Console.WriteLine(r);
Console.Write((int)r1);
Console.ReadKey();
}
In my tests, it produces the following output:
1234.00011
1234.00
1234
Note that the second line has the desired rounding, because we provided a floating point value to string.Format, so that {0:F2} would work properly. The third line has no decimal places, because we used a direct cast and includes no floating point digits whatsoever.
I'm wanting to parse a string into a nullable int list in C#
I'm able to convert it to int list bit not a nullable one
string data = "1,2";
List<int> TagIds = data.Split(',').Select(int.Parse).ToList();
say when data will be empty i want to handle that part!
Thanks
You can use following extension method:
public static int? TryGetInt32(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
Then it's simple:
List<int?> TagIds = data.Split(',')
.Select(s => s.TryGetInt32())
.ToList();
I use that extension method always in LINQ queries if the format can be invalid, it's better than using a local variable and int.TryParse (E. Lippert gave an example, follow link).
Apart from that it may be better to use data.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries) instead which omits empty strings in the first place.
Hi, I have 20 strings, each of which will have same package structure except for the class name. These strings need to be passed to method as required. Refer to the code below:
public static final String RECENT_MSG_ = "com.foo.xxs.RecentMessage";
public static final String PROJ_ = "com.foo.xxs.Proj";
public static final String FORECAST = "com.foo.xxs.Forecase";
public static final String REQUEST = "com.foo.xxs.Request";
public static final String UNAPPROVED = "com.foo.xxs.UnApproved";
public static final String UNPOSTED = "com.foo.xxs.Unposeted";
public static final String VACANT = "com.foo.xxs.Vacant";
public static final String ORG_VIOL = "com.foo.xxs.OrgViolation";
public static final String ORG_WARN = "com.foo.xxs.OrgWarning";
public static final String EMP_VIOL = "com.foo.xxs.EmpViolation";
public static final String EMP_WARN = "com.foo.xxs.EmpWarning";
public static final String TS_WARN = "com.foo.xxs.TSWarn";
public static final String TS_VIOL = "com.foo.xxs.TSViolation";
public static final String AGE_GROUP = "com.foo.xxs.AgeGroup";
private void rescheduleTasks(long _taskType,String value)
{
if(_taskType == 1000 &&(_sSchedTaskMgr.getInstance().getCurrentScheduledTaskInfo(RECENT_MSG_)==null))
{
// do something
}
}
This can also be done as follows:
public static final String RECENT_MSG_ = "RecentMessage";
public static final String PACK ="com.foo.xxs."
And concatenating the strings like so:
if(_taskType == 1000 &&(_sSchedTaskMgr.getInstance().getCurrentScheduledTaskInfo(PACK+RECENT_MSG_)==null))
Which one would be better?
They will have the same performance - the concatenation will be performed at compile time rather than execution time as both parts are constants. There will be fewer strings in the constant pool in the original version, admittedly - but that's unlikely to make a difference.
Which do you find more readable? I can't say there's much in it for me - I dislike the repetition of the first form, but equally I'm not sure I'd want to concatenate everywhere.
Another alternative is:
public static final String PACK = "com.foo.xxs."
public static final String RECENT_MSG_ = PACK + "RecentMessage";
etc - so you perform the concatenation at the point of the constant declaration. Then you can just use RECENT_MSG_ in the code, as per the first snippet, but avoid the "com.foo.xxs" duplication as per the second.
EDIT: Another option you may want to consider is using an enum.
I would go for the first version, you just make it easier for a reader to immediately see what the strings mean and what classes you're referring too. In addition, should you ever want to introduce a class from a different namespace, you'll be able to do so.
The second version, in contrast, introduces some logic which needs to be interpreted by a reader first.
If you go for the second version, use Jon's alternative instead, so that at least you still have the option to introduce classes from other namespaces.