0__ 0__ - 2 months ago 10
Scala Question

String formatting with maximum number of digits

I'm trying to format floating point numbers with a maximum number of digits, but I don't want unnecessary trailing zeroes. I thought if I use

g
instead of
f
it would work (cf. this question)

def testF(d: Double) = f"$d%1.2f"
def testG(d: Double) = f"$d%1.2g"


Now this behaves rather strangely:

testF(3.1415) // --> 3.14 ok
testF(3.1) // --> 3.10 hmmm, don't want that zero

testG(3.1415) // --> 3.1 what the ?


Ok, so perhaps I need to increase the digits by one for
g
:

def testG(d: Double) = f"$d%1.3g"

testG(3.1415) // --> 3.14 ok
testG(3.1) // --> 3.10 grmpf


So two questions—one, why the heck is
g
dropping one digit and doesn't seem to care about trailing zeroes? Two, how can I have

testX(3.1415) // --> 3.14
testX(3.1) // --> 3.1


?

Answer

You could use the java DecimalFormat but it may not please the eye:

def testX(d: Double) = new java.text.DecimalFormat("#.##").format(d)

Also to answer your first question why the heck is g dropping one digit and doesn't seem to care about trailing zeroes

For the floating-point conversions 'e', 'E', and 'f' the precision is the number of digits after the decimal separator. If the conversion is 'g' or 'G', then the precision is the total number of digits in the resulting magnitude after rounding.

Formatter details

Comments