vdeantoni
vdeantoni

Reputation: 1968

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

I am facing 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);

The output is:

0.1428571428571428571428571428571428571428571428571428571428... (200 digits)

I looked at BigDecimal documentation, and tried to set the digits when instantiating the number, then tried to set the limit with the BigDecimal.limit, but I couldn't 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

Upvotes: 5

Views: 923

Answers (2)

Roadmaster
Roadmaster

Reputation: 5357

Despite the internal representation of a big decimal, the to_s method is responsible for converting it to a string. I see to_s supports a format string:

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'

Upvotes: 0

Mark Wilkins
Mark Wilkins

Reputation: 41252

The div method allows you to specify the digits:

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

With a result of:

0.14285714285714285714285714285714285714285714285714E0

Upvotes: 7

Related Questions