Source for org.jfree.formula.util.NumberUtil

   1: package org.jfree.formula.util;
   2: 
   3: import java.math.BigDecimal;
   4: 
   5: import org.jfree.formula.EvaluationException;
   6: import org.jfree.formula.LibFormulaErrorValue;
   7: 
   8: public class NumberUtil
   9: {
  10:   public static final BigDecimal DELTA = new BigDecimal("0.000000000000000000000000000005");
  11:   
  12:   public static BigDecimal getAsBigDecimal(Number number) throws EvaluationException
  13:   {
  14:     if (number == null)
  15:     {
  16:       throw new EvaluationException(
  17:           LibFormulaErrorValue.ERROR_INVALID_ARGUMENT_VALUE);
  18:     }
  19:     
  20:     if(number instanceof BigDecimal)
  21:     {
  22:       return (BigDecimal)number;
  23:     }
  24:     else
  25:     {
  26:       return new BigDecimal(number.toString());
  27:     }
  28:   }
  29:   
  30:   public static Integer performIntRounding(BigDecimal n)
  31:   {
  32:     BigDecimal round = null;
  33:     
  34:     try
  35:     {
  36:       // no need to go further if the value is already an integer
  37:       n.setScale(0);
  38:       return new Integer(n.intValue());
  39:     }
  40:     catch(ArithmeticException e)
  41:     {
  42:       //ignore and continue
  43:     }
  44:     
  45:     if(n.signum()<0)
  46:     {
  47:       n = n.subtract(DELTA);
  48:       round = n.setScale(0, BigDecimal.ROUND_UP);
  49:     }
  50:     else
  51:     {
  52:       n = n.add(DELTA);
  53:       round = n.setScale(1, BigDecimal.ROUND_DOWN);
  54:     }
  55:     return new Integer(round.intValue());
  56:   }
  57:   
  58:   public static BigDecimal removeTrailingZeros(BigDecimal bd)
  59:   {
  60:     if(bd.signum() == 0)
  61:     {
  62:       return bd.setScale(0);
  63:     }
  64:     
  65:     try
  66:     {
  67:       while(true)
  68:       {
  69:         final int scale = bd.scale();
  70:         bd = bd.setScale(scale-1);
  71:       }
  72:     }
  73:     catch(ArithmeticException ae)
  74:     {
  75:       return bd;
  76:     }
  77:   }
  78: }