Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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

like image 936
vdeantoni Avatar asked Feb 17 '12 00:02

vdeantoni


1 Answers

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
like image 102
Mark Wilkins Avatar answered Sep 24 '22 00:09

Mark Wilkins