How to specify precision parameters using String in BigDecimal constructor?

The BigDecimal constructor takes an optional second parameter, which sets the precision digits of the object. from ruby-doc :

new (initial, digital)

The number of significant digits is like Fixnum. If omitted or 0, the number of significant digits is determined from the initial value.

However, when working with a string, this behavior does not match the description.

 BigDecimal.new('1.2345', 4).to_s('F') # 1.2345 BigDecimal.new('1.2345', 1).to_s('F') # 1.2345 

How to specify precision using BigDecimal when working with the String parameter?

+4
source share
2 answers

BigDecimal does not accept a precision parameter with a string value.

The right approach:

 BigDecimal.new("1020.567").round(2) => 1020.57 

Incorrect approach:

 BigDecimal.new(1020.567, 2) => 1000.0 
+2
source

A simple workaround would be BigDecimal.new('1.2345'.to_f, 1)

0
source

Source: https://habr.com/ru/post/1481646/


All Articles