java.lang.NumberFormatException: For input string: “0.000” [duplicate]

主宰稳场 提交于 2021-01-28 14:38:29

问题


I am trying to create a udf to take two strings as parameters; one in DD-MM-YYYY format (e.g. "14-10-2019") and the other in float format (e.g. "0.000"). I want to convert the float-like string to an int and add it to the date object to get another date which I want to return as a string.

def getEndDate = udf{ (startDate: String, no_of_days : String) =>
  val num_days = no_of_days.trim.toInt //Converts the String value to Integer
  val date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(startDate) //Parses the string date to timestamp
  calObj.setTime(date) //Sets the calendar object instance
  calObj.add(Calendar.DAY_OF_MONTH, num_days) //Adds the number of days to the start date
  val endDate = calObj.getTime().toString //Gets end date in string format
  endDate
}

When trying to run this, I am getting the following error:

Caused by: java.lang.NumberFormatException: For input string: "0.000"


回答1:


Strings like "0.0000" can't be parsed directly to integer. What you could try instead is to use first toDouble and then toInt:

no_of_days.trim.toDouble.toInt

It will round value down. If you want to round value to closest maybe you should consider using round:

no_of_days.trim.toDouble.round

Another issue with your code is, that you shouldn't use SimpleDateFormat since it's outdated. You should use LocalDate and DateTimeFormatter instead:

val date = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("dd-MM-
yyyy")) 
date.plusDays(num_days)



回答2:


I wouldn't recommend doing this but here's some examples which solve your problem.

scala> "0.00".toDouble.toInt
res0: Int = 0

scala> "2.45".toDouble.toInt
res1: Int = 2

scala> "2.5".toDouble.toInt
res2: Int = 2

scala> "2.6".toDouble.toInt
res3: Int = 2

scala> "-1".toDouble.toInt
res4: Int = -1

scala> "-1.5".toDouble.toInt
res5: Int = -1


来源:https://stackoverflow.com/questions/58871114/java-lang-numberformatexception-for-input-string-0-000

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!