Number formatting in Scala?

前端 未结 7 2101
夕颜
夕颜 2021-02-18 23:09

I have a dynamically changing input reading from a file. The numbers are either Int or Double. Why does Scala print .0 after every D

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-18 23:28

    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(:7)
            at .(:6)
            at .()
            at RequestResult$.(:4)
            at RequestResult$.()
            at RequestResult$result()
            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
    

提交回复
热议问题