Java.bigDecimal division in ruby environment
I am right script in Ruby that include java classes
require 'java'
include_class 'java.math.BigDecimal'
include_class 'java.math.RoundingMode'
during script I need to split 2 java.bigDecimal
one = BigDecimal.new("1")
number1 = BigDecimal.new("3")
number1 = one.divide(number1,RoundingMode.new(HALF_EVEN))
since i dont have intellisense in this IDE i am not sure if the syntax is correct and the runtime error is:
uninitialized constant :: HALF_EVEN
- Am I combining java object in ruby scrpit correctly?
- How do I split two java.bigDecimal objects in ruby env?
a source to share
That would be RoundingMode.HALF_EVEN
in Java; it's RoundingMode::HALF_EVEN
in Ruby. You can also use constant overloading int
(i.e. BigDecimal::ROUND_HALF_EVEN
), but overloading is enum
definitely the way to go.
You can control the scale of the quotient with 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
-
ArithmeticException
thrown duringBigDecimal.divide
-
BigDecimal
cannot represent exactly1/3
(since it has unbounded decimal expansion)
-
API references
-
java.math.RoundingMode
-
java.math.BigDecimal
A
BigDecimal
consists of an arbitrary precision integer value and a 32-bit integer scale. If zero or positive, 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 by the force the scale is negated.
a source to share