scala / scala-library-next

backwards-binary-compatible Scala standard library additions
Apache License 2.0
69 stars 17 forks source link

toBigDecimal and toBigDecimalOption #121

Open Lasering opened 2 years ago

Lasering commented 2 years ago
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 commented 2 years ago

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)
}
SethTisue commented 2 years ago

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

julienrf commented 2 years ago

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

Lasering commented 2 years ago

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