将NaN
值转换为字符串时,只需提供"NaN"
。有没有办法改变它?
类似的东西(由于重新分配给val错误而无法正常工作):
Double.NaN.toString = () => "???"
答案 0 :(得分:1)
您可以使用您带入范围的隐式类,然后为其添加一个新方法,以便在给定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)
}