"%.3f".format(1)
returns 1.000
."%.3f".format(4.0/3.0)
returns 1.333
.
Is there some easy way to have these return 1
and 1.333
? I thought the standard printf
format specified that precision as the maximum already, but apparently not in Scala.
In Scala Formatting of strings can be done utilizing two methods namely format() method and formatted() method. These methods have been approached from the Trait named StringLike.
The precision specifier defines the maximum number of significant digits that can appear in the result string. If the precision specifier is omitted or zero, the type of the number determines the default precision, as indicated in the following table. Numeric type.
String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.
You can do: Math. round(<double precision value> * 100.0) / 100.0 But Math. round is fastest but it breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)) or large integer part (e.g. round(90080070060.1d, 9)).
The default formatter used by printf seems to be a generic one that doesn't have all the same support than [DecimalFormat][1]
. You can instantiate a custom formatter along those lines:
scala> import java.text.DecimalFormat
import java.text.DecimalFormat
scala> val formatter = new DecimalFormat("#.###")
formatter: java.text.DecimalFormat = java.text.DecimalFormat@674dc
scala> formatter.format(1)
res36: java.lang.String = 1
scala> formatter.format(1.34)
res37: java.lang.String = 1.34
scala> formatter.format(4.toFloat / 3)
res38: java.lang.String = 1.333
scala> formatter.format(1.toFloat)
res39: java.lang.String = 1
See: http://docs.oracle.com/javase/tutorial/java/data/numberformat.html for more information.
"%.3f".format(1)
will throw an java.util.IllegalFormatConversionException
because of the wrong type (Float
is expected and you give a Int
).
Even if you use "%.3f".format(1.0)
, you will get 1.000
.
You can use a method like the following to obtain the expected result :
def format(x:AnyVal):String = x match {
case x:Int => "%d".format(x)
case x:Long => "%d".format(x)
case x:Float => "%.3f".format(x)
case x:Double => "%.3f".format(x)
case _ => ""
}
This method will return the expected format based on argument type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With