这个版本怎么样?
的使用Formattable
需要%s
格式,但您可以根据需要解释格式参数。
A可以在-interpolationFormattable
中间弹出,因为正常只使用或者您的 custom 。f
format
toString
formatTo
package object succinctly {
import java.util.{ Formattable, FormattableFlags, Formatter }
import scala.language.implicitConversions
implicit class Succinctly(val __thing: Double) extends AnyVal {
@inline def succinctly(s: String): String = s format fmtable(__thing)
@inline def succinctly: Formattable = fmtable(__thing)
}
private[this] val trailing = "(.*\\...*?)(0*)".r
private[this] def fmtable(a: Double) = new Formattable {
override def formatTo(formatter: Formatter, flags: Int, width: Int, precision: Int) = formatter.out append (
if (precision <= 0) a.toInt.toString
else s"%${width}.${precision}f" format a.asInstanceOf[java.lang.Double] match { case trailing(num, _) => num }
)
}
}
package succinctly {
import scala.language.postfixOps
import scala.math._
object Test extends App {
Console println (Pi succinctly "%1.2s")
Console println (3.1 succinctly "%1.2s")
Console println (3.0 succinctly "%1.2s")
Console println f"${3.1 succinctly}%1.2s"
}
}
还可以编写一个自定义插值器,将双精度值提升为无轨迹并更改%f
为%s
,尽管需要付出一些代价,因为f
-interpolator 是一个宏。