Number formatting in Scala?
scala
Solution
scala> "%1.0f" format 1.0
res3: String = 1
If your input is either `Int` or `Double`, you can do it like this:
def fmt(v: Any): String = v match {
case d : Double => "%1.0f" format d
case i : Int => i.toString
case _ => throw new IllegalArgumentException
}
Usage:
scala> fmt(1.0)
res6: String = 1
scala> fmt(1)
res7: String = 1
scala> fmt(1.0f)
java.lang.IllegalArgumentException
at .fmt(<console>:7)
at .<init>(<console>:6)
at .<clinit>(<console>)
at RequestResult$.<init>(<console>:4)
at RequestResult$.<clinit>(<console>)
at RequestResult$result(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.Dele...
Otherwise, you might use `BigDecimals`. They are slow, but they do come with the scale, so "1", "1.0" and "1.00" are all different:
scala> var x = BigDecimal("1.0")
x: BigDecimal = 1.0
scala> x = 1
x: BigDecimal = 1
scala> x = 1.0
x: BigDecimal = 1.0
scala> x = 1.000
x: BigDecimal = 1.0
scala> x = "1.000"
x: BigDecimal = 1.000
Problem
I have a dynamically changing input reading from a file. The numbers are either `Int` or `Double`. Why does Scala print `.0` after every `Double` number? Is there a way for Scala to print it the same way it reads it? Example: ``` var x:Double = 1 println (x) // This prints '1.0', I want it to print '1' x = 1.0 // This prints '1.0', which is good ``` I can't use `Int` because some of the input I get are `Double`s. I can't use `String` or `AnyVal` because I perform some math operations. Thank you,