Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there an implicit conversion from Float/Double to BigDecimal, but not from String?

Although the situation of conversion from Doubles to BigDecimals has improved a bit compared to Java

scala> new java.math.BigDecimal(0.2)
res0: java.math.BigDecimal = 0.20000000000000001110223024625156...

scala> BigDecimal(0.2)
res1: scala.math.BigDecimal = 0.2

and things like

val numbers: List[BigDecimal] = List(1.2, 3.2, 0.7, 0.8, 1.1)

work really well, wouldn't it be reasonable to have an implicit conversion like

implicit def String2BigDecimal(s: String) = BigDecimal(s)

available by default which can convert Strings to BigDecimals like this?

val numbers: List[BigDecimal] = List("1.2", "3.2", "0.7", "0.8", "1.1")

Or am I missing something and Scala resolved all "problems" of Java with using the BigDecimal constructor with a floating point value instead of a String, and BigDecimal(String) is basically not needed anymore in Scala?

like image 807
soc Avatar asked Jan 16 '11 11:01

soc


People also ask

Can we convert String to BigDecimal in Java?

We can convert a String into BigDecimal in Java using one of the below methods: BigDecimal(String) constructor. BigDecimal. valueOf() method.

What is the difference between float and BigDecimal?

float and double are two primitive types, BigDecimal is a class. It doesn't just represent numbers but operations too. A float is a decimal numeric type represented with 32 bit. A double is a 64 bit decimal number, so it can represent larger values than a float.

Is the advantage of BigDecimal over double?

Explanation: BigDecimal provides more precision as compared to double. Double is faster in terms of performance as compared to BigDecimal.

How do you convert big decimal to string?

math. BigDecimal. toString() method is used to represent the current BigDecimal by which this method is called into String form, using scientific notation if an exponent is needed.


1 Answers

This was thought of, but apparently rolled back because it created ambiguous conversions. See this thread on the scala-list.

The thread is old, but as far as I can see, string2Bigdecimal is still not defined as an implicit.

If you still want to have a local string2BigDecimal implicit for your personal use:

  • the rules for implicit scope can be found in the specification, §7.2,
  • to resolve ambiguities in favor of your string2BigDecimal, you should define it using subclassing, see this paper (§6.5) for an example, and this one (§ Avoiding Ambiguities) for an explanation.
like image 123
Francois G Avatar answered Nov 11 '22 21:11

Francois G