是否有可能改变NaN字符串表示



当将NaN值转换为字符串时,它只是给出"NaN"。有办法改变这一点吗?

类似于(由于重新赋值给val错误而无法工作):

Double.NaN.toString = () => "???"

您可以使用将其带入作用域的隐式类,然后向其添加一个新方法,以在给定NaN情况下为您提供正确格式的字符串。像这样:

object Implicits {
  implicit class PimpedDouble(d:Double){
    def toFormattedString = 
      if (d.isNaN) "something else other than NaN"
      else d.toString
  }
}
object TestDouble extends App{
  import Implicits._
  val dub = Double.NaN 
  println(dub.toFormattedString)
  println(1.234.toFormattedString)
}

最新更新