scala-library-next icon indicating copy to clipboard operation
scala-library-next copied to clipboard

toBigDecimal and toBigDecimalOption

Open Lasering opened this issue 3 years ago • 4 comments

import scala.util.control.Exception.*
extension (s: String)
  def toBigDecimal: BigDecimal = BigDecimal(s)
  def toBigDecimalOption: Option[BigDecimal] = catching(classOf[NumberFormatException]).opt(toBigDecimal)

I can make a PR if this is something that would be accepted.

Lasering avatar Apr 26 '22 18:04 Lasering

What is the correct way of doing this? Should I add a:

import scala.util.control.Exception.*
implicit final class StringOpsExtensions (private val string: String) extends AnyVal {
  def toBigDecimal: BigDecimal = BigDecimal(string)
  def toBigDecimalOption: Option[BigDecimal] = catching(classOf[NumberFormatException]).opt(toBigDecimal)
}

Lasering avatar May 07 '22 14:05 Lasering

would the desirability of having this be affected by https://docs.scala-lang.org/scala3/reference/experimental/numeric-literals.html ?

SethTisue avatar May 08 '22 16:05 SethTisue

@SethTisue an important difference is that Scala 3 feature is for literals only.

julienrf avatar May 08 '22 20:05 julienrf

@SethTisue the FromDigits machinery does not give me a clean way of doing String => Option[BigDecimal].

I only added the toBigDecimal method to make it consistent with the other toInt, toIntOption, toDouble, toDoubleOption etc methods.

Ideally these methods would be added to the StringOps class. I just don't know how to go about it in this repo.

Lasering avatar May 09 '22 00:05 Lasering