How about this version?
The use of Formattable
requires the %s
format, but you're given the formatting args to interpret as you like.
A Formattable
can pop up in the middle of an f
-interpolation, since the normal format
just uses either toString
or your custom 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"
}
}
It's also conceivable to write a custom interpolator that promotes doubles to trailless and changes %f
to %s
, though at some cost, since the f
-interpolator is a macro.