How to get precision (number of digits per decimal) from Ruby BigDecimal object?

Given the following expression for a new object BigDecimal

:

b = BigDecimal.new("3.3")

      

How can I get the precision that was determined for it? I would like to know the method that will return 1

since there will be 1 digit after the decimal digit. I ask this because b.precision

either b.digits

does not work.


Thanks to Stefan the name of the method for handling such information BigDecimal#precs

. Considering that the object BigDecimal

comes from a database, I don't know the exactness of this database object. I tried the following, but it doesn't seem to be helpful for my situation.

b = BigDecimal.new(3.14, 2)
b.precs
=> [18, 27]

      

How can I get information / argument 2

?

+3


source to share


1 answer


In Ruby 2.2.2 (and, I assume, previous versions), you cannot get back the precision that BigDecimal :: new was given . This is because it is used in some calculations; only the result of these calculations is stored. This comment to the doctor is the key:

The actual number of significant digits used in the calculation is usually greater than the specified number.

Look at the source to see what's going on. BigDecimal_new retrieves the parameters, enforces some constraints and checks the type, and calls VpAlloc. mf contains the digits argument in BigDecimal :: new:

return VpAlloc(mf, RSTRING_PTR(iniValue));

      

In VpAlloc , mf gets renamed to mx:



VpAlloc(size_t mx, const char *szVal)

      

The very first thing MxAlloc does is round mx (precision) to the nearest multiple of BASE_FIG:

mx = (mx + BASE_FIG - 1) / BASE_FIG;    /* Determine allocation unit. */
if (mx == 0) ++mx;

      

BASE_FIG is equivalent to RMPD_COMPONENT_FIGURES , which has a platform dependent value of 38, 19, 9, 4, or 2.

There are further calculations with mx before they are stored in the BigDecimal being created, but we can already see that the original argument passed to :: new is destroyed and not restored.

+2


source







All Articles