Home > Mobile >  Format String to Float with two decimal places
Format String to Float with two decimal places

Time:06-20

I have this code ( which is not working unfortunately):

object Number
{
    case class Number(number: Float)

    def fromString(value: String): Either[Throwable, Number] =
    {
        Try("%.2f".format(value).replace(',', '.').toFloat)
            .map(Number)
            .toEither
    }
}


def main(args: Array[String]): Unit = Number.fromString("100,555")

my goal is to have a Float, that looks like this:

100.56

But for now the output is:

Left(java.util.IllegalFormatConversionException: f != java.lang.String)

So my questin is: How can I get my wanted output?

Or is there a function to format and round a number like number_format in PHP

CodePudding user response:

The conversion can be done like this:

def fromString(value: String): Either[Throwable, Number] =
    Try(Number(value.replace(',', '.').toFloat))
        .toEither

Rounding a binary to a decimal internally is a bad idea, but this is how it would work:

def fromString(value: String): Either[Throwable, Number] = {
  Try(
    Number(math.round(value.replace(',', '.').toFloat * 100.0) / 100.0f)
  ).toEither
}
  • Related