2

I right script in Ruby that include java classes

require 'java'
include_class 'java.math.BigDecimal'
include_class 'java.math.RoundingMode'

during the script I need to divide 2 java.bigDecimal

 one = BigDecimal.new("1")
 number1 = BigDecimal.new("3")
 number1 = one.divide(number1,RoundingMode.new(HALF_EVEN))

since I don't have intellisense in this IDE I'm not sure the syntax is right and the runtime error is:

uninitialized constant::HALF_EVEN

  1. do I combine java object in the ruby scrpit in the right way?
  2. how should I divide two java.bigDecimal object in ruby env?
DJ.
  • 6,664
  • 1
  • 33
  • 48
Eyal
  • 21
  • 1

2 Answers2

1

Try

number1 = one.divide(number1, RoundingMode::Half_EVEN)
DJ.
  • 6,664
  • 1
  • 33
  • 48
0

It would've been RoundingMode.HALF_EVEN in Java; it's RoundingMode::HALF_EVEN in Ruby. You may also be able to use the int constants overload (i.e. BigDecimal::ROUND_HALF_EVEN), but the enum overload is definitely the way to go.

You can control the scale of the quotient using the divide(BigDecimal divisor, int scale, RoundingMode mode) overload.

Here's a Java snippet:

    BigDecimal one = BigDecimal.ONE;
    BigDecimal three = BigDecimal.valueOf(3);

    System.out.println(one.divide(three, 10, RoundingMode.DOWN));
    // prints "0.3333333333"

    System.out.println(one.divide(three, 10, RoundingMode.UP));
    // prints "0.3333333334"

    System.out.println(one.divide(three, 333, RoundingMode.UNNECESSARY));
    // throws java.lang.ArithmeticException: Rounding necessary

Related questions

API links

  • java.math.RoundingMode
  • java.math.BigDecimal

    A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • In Ruby, to access static / class constants the notation is '::'. And JRuby automatically transalate the Java syntax to Ruby syntax accordingly. – DJ. May 02 '10 at 22:40
  • Thanks! it works. a small follow up question - now when I divide 1/3 it returns 0 or 1 (according to rounding defined). is there a way that I can tune the accurate fraction, for example 1/3 = 0.3333 or 5/7=0.7142 – Eyal May 09 '10 at 18:07
  • @Eyal: use the `scale` parameter. See added examples. – polygenelubricants May 10 '10 at 01:24