How to increase the number of decimal digits when converting BigDecimal to String?

I have a problem with BigDecimal.

This code:

x = BigDecimal.new('1.0') / 7
puts x.to_s

outputs:

0.142857142857142857E0

I want to increase the number of digits.

In JAVA, I could do:

BigDecimal n = new BigDecimal("1");
BigDecimal d = new BigDecimal("7");

n = n.divide(d,200, RoundingMode.HALF_UP);

System.out.println(n);

Conclusion:

0.1428571428571428571428571428571428571428571428571428571428... (200 digits)

I looked at the BigDecimal documentation and tried to set the digits when creating the number instance, and then tried to set the limit using BigDecimal.limit, but I could not print more than 18 digits.

What am I missing?

I am running ruby ​​1.9.3p0 (2011-10-30) [i386-mingw32] on Windows 7 64bits

+5
source share
2 answers

The method divallows you to specify the numbers:

x = BigDecimal.new('1.0').div( 7, 50 )
puts x

As a result:

0.14285714285714285714285714285714285714285714285714E0
+7
source

, to_s . , to_s :

Converts the value to a string.

The default format looks like 0.xxxxEnn.

The optional parameter s consists of either an integer; or an optional ‘+’ or ‘ ’, followed by an optional number, followed by an optional ‘E’ or ‘F’.

If there is a ‘+’ at the start of s, positive values are returned with a leading ‘+’.

A space at the start of s returns positive values with a leading space.

If s contains a number, a space is inserted after each group of that many fractional digits.

If s ends with an ‘E’, engineering notation (0.xxxxEnn) is used.

If s ends with an ‘F’, conventional floating point notation is used.

Examples:

BigDecimal.new('-123.45678901234567890').to_s('5F') -> '-123.45678 90123 45678 9'

BigDecimal.new('123.45678901234567890').to_s('+8F') -> '+123.45678901 23456789'

BigDecimal.new('123.45678901234567890').to_s(' F') -> ' 123.4567890123456789'
0

All Articles