Groovy: Converting a string to integer gives NumberFormatException - string

I am trying to get a date from this text:
{InstantSeconds=1581504140},ISO,Europe/Paris resolved to 2020-02-12T11:42:20
I tried doing
def text = "{InstantSeconds=1581504140},ISO,Europe/Paris resolved to 2020-02-12T11:42:20"
text = text.replaceAll("[^\\d.]", "")
text = text.substring(10)
println "${text}"
int result= Integer.parseInt("${text}");
println result
But I'm getting
java.lang.NumberFormatException: For input string: "20200212114220"
I'm using this (for practice) https://groovyconsole.appspot.com/
Does anyone know why that happens?

The value is too long for an integer. Use a Long datatype:
Long result = text.toLong()
assert result.class.name == 'java.lang.Long'
assert result == 20200212114220

Related

Trying to convert input string to integer in Swift

I am trying to write a program that takes a number input from user and stores it into a string, then i am trying to convert that string to integer for further use. Whenever i convert it, it displays nil for the integer value but will print the input when kept as a string. Here is my code so far. This is my first time trying to write in swift.
import Foundation
func input() -> String{
var keyboard = NSFileHandle.fileHandleWithStandardInput()
var inputData = keyboard.availableData
return NSString(data: inputData, encoding:NSUTF8StringEncoding) as! String
}
print("What is a number: ")
let user: String? = input()
print("You typed: " + user!)
var num = Int(user!)
print("Your number was" ,(num))
The Int function returns an optional integer, so if your string can't be converted it will return nil. If you assign it a value that it can convert, you'll get the result you're looking for:
let user: String = "5"
var num = Int(user)
if let num = num {
print("Your number was \(num)")
} else {
print("Your number is nil")
}
Also, your input function is returning a String, but you're defining the user variable as an optional String?
After searching around and trying different things, I was able to do exactly what I wanted after doing...
var user = input()
var newString = user.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())

How to convert a String to an Integer in Groovy [duplicate]

This question already has answers here:
Converting a string to int in Groovy
(13 answers)
Closed 7 years ago.
How can I convert a String (which is a number) to integer in Groovy.
I am using Groovy 2.4.5. Here is a sample code which throws exception:
Code:
def String a = "CHECK";
def String b = "3.5";
def String c = "7.5";
println "Is a number ? " + a.isNumber();
println "Is b number ? " + b.isNumber();
println "Is c number ? " + c.isNumber();
if (a.equals("CHECK"))
{
def int x = b.toInteger();
def int y = c.toInteger();
}
println b+c;
Output (with exceptions):
Is a number ? false
Is b number ? true
Is c number ? true
Exception thrown
java.lang.NumberFormatException: For input string: "3.5"
at myAdditionLogic.run(myAdditionLogic.groovy:12)
integer is a 32-bit number that doesn’t include a decimal point. You probably want a decimal data type, like Double.
Try this:
String a = "CHECK";
String b = "3.5";
String c = "7.5";
println "Is a number ? " + a.isNumber();
println "Is b number ? " + b.isNumber();
println "Is c number ? " + c.isNumber();
if (a.equals("CHECK"))
{
def x = b as Double;
def y = c as Double;
println x + y
}

Convert String to Long using BufferReader

I'm trying to convert my input read Strings to long (Long). I've tried the valueof() and Long.Parslong(String s) but no luck. Im not sure what is going on. I can certainly print the String but cannot convert to Long ):
while ((line = br.readLine()) != null) {
String[] sheet = line.split(cvsSplitBy); //comma as separator
if(isNumeric(sheet[3])){ //parse into integer, only if first col is num
int n = Integer.parseInt(sheet[0]);
int pop = Integer.parseInt(sheet[3]);
System.out.println(sheet[4]);
System.out.println(sheet[4].getClass().getName());
Long lon = Long.valueOf(sheet[4]); //THIS IS WHERE THE ERROR OCCURS
......skip
The Error is the usual NumberFormatException
Exception in thread "main" java.lang.NumberFormatException: For input string: "34.95"
Any ideas? Thanks Aj
Focus on the description of the exception.
For input string: "34.95"
It has a Decimal value, which can't convert into a Long. You could either use Double.valueOf("34.95") or do a validation for non integer values.

How to check whether the input is a number or string by using isNan() in groovy

Hello i am a beginner to groovy i am cofused how to check whether the given input is a number or not i tried the following
def a= ' 12.571245ERROR'
if(a.isNan()==0)
{
println("not a number")
}
else
{
println("number")
}
Kindly help me how to use isNan in groovy.I googled it lot but didnt find any result . Thanks in advance
Groovy's String::isNumber() to the rescue:
def a = "a"
assert !a.isNumber()
def b = "10.90"
assert b.isNumber()
assert b.toDouble() == 10.90
To answer your question, I would not consider isNan(). It is mentioned on the web, but it does not appear in the String doc for the GDK.
Consider this:
def input = "12.37"
def isNumber = input.isDouble()
println "isNumber : ${isNumber}"
Or use something that is more Java-esque:
def input = "12.37error"
def isNumber = false
try {
double value = Double.parseDouble(input)
isNumber = true
} catch (Exception ex) {
}
println "isNumber : ${isNumber}"
You can try to cast it to number and catch an exception if its not a number
def a= ' 12.571245ERROR'
try {
a as Double
println "a is number"
}catch (e) {
println "a is not a number"
}
Or
if(a instanceof Number)
println "Number"
else
println "NaN"
Although keep in mind, in the second way of checking it, it would fail even if a is a valid number but in a String like "123". 123 is Number but "123" is not.
This will fail for the number format with commas (eg: 10,00,000)
def aNumber = "10,00,000"
aNumber.isNumber() and aNumber.isDouble() give answer as false.

Java-Servlets: String null or "null"

String says its not null but then later throw NullPointerException
I had this problem(see the link), where I was sure that a String is null, but in fact the String was "null"
jcasso told me:
Since you get the string from a
servlet i can say that this is normal.
Java converts a null string to a
"null" string on some conditions.
When this situations appear?
Mostly when you use string concatenation or String.valueOf():
String x = null;
String y = x + ""; // y = "null"
String z = String.valueOf(x); // z = "null"
(There are similar variants, such as using StringBuilder.append((String) null).)

Resources