Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String formatting in scala - maximum decimal precision

Tags:

scala

"%.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.

like image 836
Ben Dilts Avatar asked Nov 20 '11 17:11

Ben Dilts


People also ask

How can you format a string 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.

What is string precision?

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.

How do I format a string to two decimal places?

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 %.

How do you round off decimals in Scala?

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)).


2 Answers

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.

like image 82
huynhjl Avatar answered Oct 03 '22 11:10

huynhjl


"%.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.

like image 44
David Avatar answered Oct 03 '22 11:10

David