jesus g_force Harris
jesus g_force Harris

Reputation: 516

Formatting a number by passing number of decimal places as a parameter in Scala

(In Scala) I've been trying to create a function that converts a Double to a certain number of decimal points. If I wanted it to return a String to 2 decimal places I would do this:

    def roundBy2(num: Double): String = f"$num%1.2f"

But if I wanted to pass the number of decimal places through a parameter my first attempt might be:

    def roundBy(num: Double)(dp: Int): String = f"$num%1.${dp}f"

But this throws up:

Missing conversion operator in '%1'; use %% for literal %, %n for newline def roundBy(num: Double)(dp: Int): String = f"$num%1.${dp}f"

I know that when using interpolators I don't have to use curly braces when referencing a value inside the quotations but of course that would just leave f"$num%1.$dpf" and I would be mistaken for trying to use a value that hasn't been declared, i.e. $dpf

I feel sure that this is attainable in this way but I am lacking the syntax so I'm hoping that there is an easy fix. Thanks

Upvotes: 2

Views: 513

Answers (1)

Federico Pellegatta
Federico Pellegatta

Reputation: 4017

You could just use .format(num) instead:

def roundBy(num: Double)(dp: Int): String = s"%1.${dp}f".format(num)

Upvotes: 2

Related Questions