Java Code Examples for java.math.BigDecimal#toString()

The following examples show how to use java.math.BigDecimal#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BigDecimalMath.java    From nd4j with Apache License 2.0 6 votes vote down vote up
/**
 * Power function.
 *
 * @param x Base of the power.
 * @param y Exponent of the power.
 * @return x^y.
 * The estimation of the relative error in the result is |log(x)*err(y)|+|y*err(x)/x|
 */
static public BigDecimal pow(final BigDecimal x, final BigDecimal y) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        throw new ArithmeticException("Cannot power negative " + x.toString());
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else {
        /* return x^y = exp(y*log(x)) ;
         */
        BigDecimal logx = log(x);
        BigDecimal ylogx = y.multiply(logx);
        BigDecimal resul = exp(ylogx);
        /* The estimation of the relative error in the result is |log(x)*err(y)|+|y*err(x)/x|
         */
        double errR = Math.abs(logx.doubleValue() * y.ulp().doubleValue() / 2.)
                        + Math.abs(y.doubleValue() * x.ulp().doubleValue() / 2. / x.doubleValue());
        MathContext mcR = new MathContext(err2prec(1.0, errR));
        return resul.round(mcR);
    }
}
 
Example 2
Source File: CCSystem.java    From FCMFrame with Apache License 2.0 6 votes vote down vote up
private void drawXUnitLine(Graphics2D g2d, BigDecimal val) {
    /* Don't draw anything at the origin. */
    if (val.doubleValue() == 0.0) return;
    
    /* val is "small" if -10^7 < val < 10^7. */
    BigDecimal big = BigDecimal.valueOf(10000000);
    boolean small = val.compareTo(big) < 0
            && val.compareTo(big.negate()) > 0;
    
    /* 
     * When val is not "small", BigDecimal's toString does not use
     * scientific notation, so Double's toString is used instead.
     */
    String strval;
    if (small) strval = val.toString();
    else strval = Double.toString(val.doubleValue());
    
    Point2D.Double p2d = new Point2D.Double(val.doubleValue(), origin2d.y);
    Point p = translate(p2d);
    
    int strValPixels = 7 * strval.length();
    int offset = (minY >= -translateY(40)) ? -10 : 20;

    g2d.drawLine(p.x, p.y-ulSize, p.x, p.y+ulSize);
    g2d.drawString(strval, p.x - strValPixels/2, p.y + offset);
}
 
Example 3
Source File: BiAnService.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
@Override
public ResultSet<String> buy(CoinSpot symbol, BigDecimal price, BigDecimal amount, String aKey, String sKey) {
    //TODO 未测试
    BinanceApiClientFactory binanceApiClientFactory = BinanceApiClientFactory.newInstance();
    BinanceApiRestClient binanceApiRestClient = binanceApiClientFactory.newRestClient();

    //处理symbol
    String sy = symbol.toString().replace("_", "").toUpperCase();

    NewOrder newOrder = new NewOrder(sy, OrderSide.BUY, OrderType.LIMIT, TimeInForce.GTC,amount.toString());
    NewOrderResponse newOrderResponse = binanceApiRestClient.newOrder(newOrder);
    System.out.println(newOrderResponse);
    String res = JSONUtils.obj2json(newOrderResponse);
    System.out.println(res);

    return null;
}
 
Example 4
Source File: MyTime.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Convert decimal value to datetime value with a warning.
 *
 * @param decimal The value to convert from.
 * @param flags   Conversion flags.
 * @return False on success, true on error.
 * @param[out] ltime The variable to convert to.
 */
public static boolean myDecimalToDatetimeWithWarn(BigDecimal decimal, MySQLTime ltime, long flags) {
    LongPtr warnings = new LongPtr(0);
    String sbd = decimal.toString();
    String[] sbds = sbd.split("\\.");
    long intPart = Long.parseLong(sbds[0]);
    long secondPart = 0;
    if (sbds.length == 2)
        secondPart = Long.parseLong(sbds[1]);
    if (numberToDatetime(intPart, ltime, flags, warnings) == -1) {
        ltime.setZeroTime(MySQLTimestampType.MYSQL_TIMESTAMP_ERROR);
        return true;
    } else if (ltime.getTimeType() == MySQLTimestampType.MYSQL_TIMESTAMP_DATE) {
        /**
         * Generate a warning in case of DATE with fractional part:
         * 20011231.1234 . '2001-12-31' unless the caller does not want the
         * warning: for example, CAST does.
         */
        if (secondPart != 0 && (flags & TIME_NO_DATE_FRAC_WARN) == 0) {
            warnings.set(warnings.get() | MYSQL_TIME_WARN_TRUNCATED);
        }
    } else if ((flags & TIME_NO_NSEC_ROUNDING) == 0) {
        ltime.setSecondPart(secondPart);
    }
    return false;
}
 
Example 5
Source File: BitfinexWithdrawalRequest.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
/**
 * Constructor
 *
 * @param nonce
 * @param withdrawType
 * @param walletSelected
 * @param amount
 * @param address
 */
public BitfinexWithdrawalRequest(
    String nonce,
    String withdrawType,
    String walletSelected,
    BigDecimal amount,
    String address,
    String paymentId) {

  this.request = "/v1/withdraw";
  this.nonce = String.valueOf(nonce);
  this.options = "[]";
  this.withdrawType = withdrawType;
  this.walletSelected = walletSelected;
  this.amount = amount.toString();
  this.address = address;
  this.paymentId = paymentId;
}
 
Example 6
Source File: BigDecimalMath.java    From nd4j with Apache License 2.0 5 votes vote down vote up
/**
 * The square root.
 *
 * @param x the non-negative argument.
 * @return the square root of the BigDecimal rounded to the precision implied by x.
 */
static public BigDecimal sqrt(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        throw new ArithmeticException("negative argument " + x.toString() + " of square root");
    }
    return root(2, x);
}
 
Example 7
Source File: Item.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
protected String valStringFromDecimal() {
    BigDecimal bd = valDecimal();
    if (nullValue)
        return null; /* purecov: inspected */
    if (bd == null)
        return null;
    return bd.toString();
}
 
Example 8
Source File: StringUtilities.java    From CRF with MIT License 5 votes vote down vote up
public static String bigDecimalToString(BigDecimal d)
{
	if (d.compareTo(ArithmeticUtilities.DOUBLE_MAX)<=0)
	{
		return String.format("%-3.4f", d.doubleValue());
	}
	else
	{
		return d.toString();
	}
}
 
Example 9
Source File: ItemDecimalTypeCast.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String valStr() {
    BigDecimal tmp = valDecimal();
    if (nullValue)
        return null;
    return tmp.toString();
}
 
Example 10
Source File: PriceUtil.java    From java-trader with Apache License 2.0 5 votes vote down vote up
public static String long2str(long p, int scale){
    if ( p==Long.MAX_VALUE ) {
        return "N/A";
    }
    /*
    StringBuilder text = new StringBuilder(32);
    if ( p<0 ){
        text.append("-");
        p = -1*p;
    }
    text.append(p/10000);
    long f = p%10000;
    if ( f!=0 ){
        String s = ""+f;
        int slen = s.length();
        switch(scale){
        case 0:
            break;
        case 1:
            text.append(".").append(s.substring(0, Math.min(1, s.length())));
            break;
        case 2:
            text.append(".").append(s.substring(0, Math.min(2, s.length())));
            break;
        case 3:
            text.append(".").append(s.substring(0, Math.min(3, s.length())));
            break;
        case 4:
            text.append(".").append(s.substring(0, Math.min(4, s.length())));
            break;
        default:
            throw new RuntimeException("Invalid scale for price "+p);
        }
    }
    return text.toString();
     */
    BigDecimal bd = new BigDecimal(p);
    bd = bd.divide(new BigDecimal(PRICE_SCALE)).setScale(scale,RoundingMode.HALF_UP);
    return bd.toString();
}
 
Example 11
Source File: BigDecimalMath.java    From nd4j with Apache License 2.0 5 votes vote down vote up
/**
 * The integer root.
 *
 * @param n the positive argument.
 * @param x the non-negative argument.
 * @return The n-th root of the BigDecimal rounded to the precision implied by x, x^(1/n).
 */
static public BigDecimal root(final int n, final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        throw new ArithmeticException("negative argument " + x.toString() + " of root");
    }
    if (n <= 0) {
        throw new ArithmeticException("negative power " + n + " of root");
    }
    if (n == 1) {
        return x;
    }
    /* start the computation from a double precision estimate */
    BigDecimal s = new BigDecimal(Math.pow(x.doubleValue(), 1.0 / n));
    /* this creates nth with nominal precision of 1 digit
     */
    final BigDecimal nth = new BigDecimal(n);
    /* Specify an internal accuracy within the loop which is
     * slightly larger than what is demanded by ’eps’ below.
     */
    final BigDecimal xhighpr = scalePrec(x, 2);
    MathContext mc = new MathContext(2 + x.precision());
    /* Relative accuracy of the result is eps.
     */
    final double eps = x.ulp().doubleValue() / (2 * n * x.doubleValue());
    for (;;) {
        /* s = s -(s/n-x/n/s^(n-1)) = s-(s-x/s^(n-1))/n; test correction s/n-x/s for being
         * smaller than the precision requested. The relative correction is (1-x/s^n)/n,
         */
        BigDecimal c = xhighpr.divide(s.pow(n - 1), mc);
        c = s.subtract(c);
        MathContext locmc = new MathContext(c.precision());
        c = c.divide(nth, locmc);
        s = s.subtract(c);
        if (Math.abs(c.doubleValue() / s.doubleValue()) < eps) {
            break;
        }
    }
    return s.round(new MathContext(err2prec(eps)));
}
 
Example 12
Source File: IceFormat.java    From iceroot with Apache License 2.0 5 votes vote down vote up
/**
 * 数字格式化
 * 
 * @param num 数字值
 * @param precision 小数点位数
 * @param roundingMode 舍入模式
 * @return 格式化后的数字
 */
public static String format(String num, int precision, RoundingMode roundingMode) {
    if (num == null) {
        return null;
    }
    BigDecimal decimal = new BigDecimal(num);
    decimal = decimal.setScale(precision, roundingMode);
    String result = decimal.toString();
    return result;
}
 
Example 13
Source File: ClientViewServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
protected String getTotalRemainingIndicator(User user) {
  List<Filter> filters = getTotalRemainingOfUser(user);
  List<Invoice> invoiceList = Filter.and(filters).build(Invoice.class).fetch();
  if (!invoiceList.isEmpty()) {
    BigDecimal total =
        invoiceList
            .stream()
            .map(Invoice::getAmountRemaining)
            .reduce((x, y) -> x.add(y))
            .orElse(BigDecimal.ZERO);
    return total.toString() + invoiceList.get(0).getCurrency().getSymbol();
  }
  return BigDecimal.ZERO.toString();
}
 
Example 14
Source File: AmazonSimpleDBUtil.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
public static String encodeRealNumberRange(BigDecimal number, int maxNumDigits, BigDecimal offsetValue) {
	final BigDecimal offsetNumber = number.add(offsetValue);
	final String longString = offsetNumber.toString();
	final int numZeroes = maxNumDigits - longString.length();
	final int paddedSize = numZeroes + longString.length();
	final StringBuilder strBuffer = new StringBuilder(paddedSize);
	for(int i = 0; i < numZeroes; i++) {
		strBuffer.insert(i, '0');
	}
	strBuffer.append(longString);

	return strBuffer.toString();
}
 
Example 15
Source File: Price.java    From java-stellar-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns price as a string.
 */
public String toString() {
    MathContext mc = MathContext.DECIMAL64;
    BigDecimal result = new BigDecimal(this.n).divide(new BigDecimal(this.d), mc);

    return result.toString();
}
 
Example 16
Source File: SqlFunctions.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** CAST(DECIMAL AS VARCHAR). */
public static String toString(BigDecimal x) {
  final String s = x.toString();
  if (s.equals("0")) {
    return s;
  } else if (s.startsWith("0.")) {
    // we want ".1" not "0.1"
    return s.substring(1);
  } else if (s.startsWith("-0.")) {
    // we want "-.1" not "-0.1"
    return "-" + s.substring(2);
  } else {
    return s;
  }
}
 
Example 17
Source File: CostToken.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public String[] unparse(LoadContext context, Ability ability)
{
	BigDecimal bd = context.getObjectContext().getObject(ability, ObjectKey.SELECTION_COST);
	if (bd == null)
	{
		return null;
	}
	return new String[]{bd.toString()};
}
 
Example 18
Source File: Matrix.java    From JavaMainRepo with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param args
 *            Not used.
 */
public static void main(final String[] args) {
	BigDecimal[][] a = random(2, 3);
	BigDecimal[][] b = random(2, 2);
	BigDecimal[][] c;
	MatrixOperations singletonMatrixOperations = 
			MatrixOperations.getInstance();
	show(a);
	System.out.println();
	show(b);
	System.out.println("The sum of the 2 matrices is: ");
	c = singletonMatrixOperations.add(a, b);
	if (c != null) {
		show(c);
	}
	System.out.println();
	System.out.println("The difference of the 2 matrices is: ");
	c = singletonMatrixOperations.subtract(a, b);
	if (c != null) {
		show(c);
	}
	System.out.println();
	System.out.println("The product of the 2 matrices is: ");
	c = singletonMatrixOperations.multiply(a, b);
	if (c != null) {
		show(c);
	}
	System.out.println();
	BigDecimal numberA = new BigDecimal("10");
	System.out.println("The product of the first matrix with "
	+ numberA + " is:");
	c = singletonMatrixOperations.multiplyScalar(a, numberA);
	if (c != null) {
		show(c);
	}
	System.out.println();
	BigDecimal numberB = new BigDecimal("10");
	System.out.println("The product of the second matrix with "
	+ numberB + " is:");
	c = singletonMatrixOperations.multiplyScalar(b, numberB);
	if (c != null) {
		show(c);
	}
	System.out.println();
	System.out.println("The determinant of the matrix A is:");
	BigDecimal det = singletonMatrixOperations.determinant(a);
	String determinantA = det.setScale(
			5, BigDecimal.ROUND_CEILING).toString();
	//Takes only 5 digits after the point.
	System.out.println(determinantA);
	System.out.println();
	System.out.println("The determinant of the matrix B is: ");
	BigDecimal detB = singletonMatrixOperations.determinant(b);
	String determinantB = detB.setScale(
			5, BigDecimal.ROUND_CEILING).toString();
	//Takes only 5 digits after the point.
	System.out.println(determinantB);
	System.out.println();
	System.out.print("The matrices A and B are equal?");
	System.out.println();
	System.out.println(singletonMatrixOperations.areEqual(a, b) 
			? "Yes!" : "No!");
	System.out.println();
	System.out.print("Is A zero matrix? ");
	System.out.println();
	System.out.println(singletonMatrixOperations.isZeroMatrix(a) 
			? "Yes!" : "No!");
	System.out.println();
	System.out.print("Is B zero matrix? ");
	System.out.println();
	System.out.println(singletonMatrixOperations.isZeroMatrix(b) 
			? "Yes!" : "No!");
	System.out.println();
	System.out.print("Is A identity matrix? ");
	System.out.println();
	System.out.println(singletonMatrixOperations.isIdentityMatrix(a) 
			? "Yes!" : "No!");
	System.out.println();
	System.out.print("Is B identity matrix? ");
	System.out.println();
	System.out.println(singletonMatrixOperations.isIdentityMatrix(b) 
			? "Yes!" : "No!");
	System.out.println();

	System.out.print("The fill degree of the matrix A is:");
	BigDecimal fillDegreeA = singletonMatrixOperations.fillDegree(a);
	String degreeA = fillDegreeA.toString();
	System.out.println(degreeA + "%");
	System.out.print("The fill degree of the matrix B is:");
	BigDecimal fillDegreeB = singletonMatrixOperations.fillDegree(b);
	String degreeB = fillDegreeB.toString();
	System.out.println(degreeB + "%");

}
 
Example 19
Source File: StringValueFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public String createFromBigDecimal(BigDecimal d) {
    return d.toString();
}
 
Example 20
Source File: DepotItemController.java    From jshERP with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 导出excel表格
 * @param currentPage
 * @param pageSize
 * @param projectId
 * @param monthTime
 * @param headIds
 * @param materialIds
 * @param request
 * @param response
 * @return
 */
@GetMapping(value = "/exportExcel")
public void exportExcel(@RequestParam("currentPage") Integer currentPage,
                        @RequestParam("pageSize") Integer pageSize,
                        @RequestParam("depotId") Long depotId,
                        @RequestParam("monthTime") String monthTime,
                        @RequestParam("name") String name,
                        @RequestParam("model") String model,
                        HttpServletRequest request, HttpServletResponse response) throws Exception {
    Long tenantId = Long.parseLong(request.getSession().getAttribute("tenantId").toString());
    String timeA = monthTime+"-01 00:00:00";
    String timeB = Tools.lastDayOfMonth(monthTime)+" 23:59:59";
    try {
        List<DepotItemVo4WithInfoEx> dataList = depotItemService.findByAll(StringUtil.toNull(name), StringUtil.toNull(model),
                timeB, (currentPage-1)*pageSize, pageSize);
        //存放数据json数组
        String[] names = {"名称", "型号", "单位", "单价", "上月结存数量", "入库数量", "出库数量", "本月结存数量", "结存金额"};
        String title = "库存报表";
        List<String[]> objects = new ArrayList<String[]>();
        if (null != dataList) {
            for (DepotItemVo4WithInfoEx diEx : dataList) {
                Long mId = diEx.getMId();
                String[] objs = new String[9];
                objs[0] = diEx.getMName().toString();
                objs[1] = diEx.getMModel().toString();
                objs[2] = diEx.getMaterialUnit().toString();
                objs[3] = diEx.getPurchaseDecimal().toString();
                objs[4] = depotItemService.getStockByParam(depotId,mId,null,timeA,tenantId).toString();
                objs[5] = depotItemService.getInNumByParam(depotId,mId,timeA,timeB,tenantId).toString();
                objs[6] = depotItemService.getOutNumByParam(depotId,mId,timeA,timeB,tenantId).toString();
                BigDecimal thisSum = depotItemService.getStockByParam(depotId,mId,null,timeB,tenantId);
                objs[7] = thisSum.toString();
                objs[8] = thisSum.multiply(diEx.getPurchaseDecimal()).toString();
                objects.add(objs);
            }
        }
        File file = ExcelUtils.exportObjectsWithoutTitle(title, names, title, objects);
        ExportExecUtil.showExec(file, file.getName() + "-" + monthTime, response);
    } catch (Exception e) {
        e.printStackTrace();
    }
}