1

I am a Scala noob. I am converting a python script to Scala. In one of my routine I am reading from a CSV file. The column is in scientific notation format. My code in python is:

"%i" % float(line[USER_ID]) where line[USER_ID] = "9.04E09"

This converts to "9040000000". How do I do this in Scala?

Athari
  • 33,702
  • 16
  • 105
  • 146
Rolly Ferolino
  • 101
  • 2
  • 9

3 Answers3

4

Using Scala 2.10 String interpolation:

scala> val numString = "9.04E09"
numString: String = 9.04E09

scala> val num = numString.toFloat
num: Float = 9.04E9

scala> val formatted = f"$num%1.0f"
formatted: String = 9040000000

If you are not using Scala 2.10, you'll have to do the String formatting yourself, which isn't really that different:

scala> val formatted = format("%1.0f", num)
formatted: String = 9040000000

I'm also assume your data is sanitized (i.e., no validation/exception is being done, in case your input string doesn't parse to a valid float).

Jack Leow
  • 21,945
  • 4
  • 50
  • 55
  • I should mention that I assumed you want the output to remain a String, since that's what you have in your original Python version. If you want it to be an actual numeric type, Brian and Eran's answers are probably better. – Jack Leow Jul 09 '13 at 23:43
1

The Java way: (see here as well Java parse a number in exponential notation)

java.lang.Double.valueOf("9.04E09").longValue()

Another way in Scala:

"9.04E09".toDouble.longValue

Or

"9.04E09".toDouble.formatted("%.0f")
Community
  • 1
  • 1
Eran Medan
  • 44,555
  • 61
  • 184
  • 276
0

You can use the Java API.

scala> val d = new java.lang.Double("9.04E09")
d: Double = 9.04E9

scala> val l = d.longValue
l: Long = 9040000000
Brian
  • 20,195
  • 6
  • 34
  • 55