将BigDecimal转换为String时,如何增加小数位数?

时间:2012-02-17 00:28:29

标签: ruby

我遇到了BigDecimal的问题。

此代码:

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

输出:

0.142857142857142857E0

我想增加位数。

在JAVA中,我可以做到:

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

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

System.out.println(n);

输出结果为:

0.1428571428571428571428571428571428571428571428571428571428... (200 digits)

我看了BigDecimal documentation,并试图在实例化数字时设置数字,然后尝试使用BigDecimal.limit设置限制,但我打印的数字不能超过18位。

我错过了什么?

我在Windows 7 64位上运行ruby 1.9.3p0(2011-10-30)[i386-mingw32]

2 个答案:

答案 0 :(得分:7)

div方法允许您指定数字:

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

结果:

0.14285714285714285714285714285714285714285714285714E0

答案 1 :(得分:0)

尽管内部表示大小数,但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'