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

The following examples show how to use java.math.BigDecimal#toPlainString() . These examples are extracted from open source projects. 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
@ValueConverter(rule = "Fraction")
public IValueConverter<BigDecimal> Fraction() {
	return new AbstractNullSafeConverter<BigDecimal>(){
		@Override
		protected BigDecimal internalToValue(String string, INode node) {
			String[] splitted = string.split("/");
			if (splitted.length > 1) {
				return new BigDecimal(splitted[0].trim()).divide(new BigDecimal(splitted[1].trim()));
			}
			return new BigDecimal(string);
		}

		@Override
		protected String internalToString(BigDecimal value) {
			BigDecimal bd = value;
			int scale = bd.scale();
			if (scale <= 0) {
				return bd.toPlainString();
			}
			bd = bd.multiply(BigDecimal.valueOf(1, -1 * scale));
			return bd.toPlainString() + '/' + BigDecimal.valueOf(1, -1 * scale).toPlainString();
		}};
}
 
Example 2
@Override
public String toString(Object value) throws ValueConverterException {
    if (value == null) {
        throw new ValueConverterException("Value may not be null.", null, null);
    }
    if (value instanceof String) {
        return toEscapedString((String) value);
    }
    if (value instanceof BigDecimal) {
        BigDecimal decimalValue = (BigDecimal) value;
        return decimalValue.toPlainString();
    }
    if (value instanceof Boolean) {
        return ((Boolean) value).toString();
    }
    throw new ValueConverterException("Unknown value type: " + value.getClass().getSimpleName(), null, null);
}
 
Example 3
Source Project: jphp   File: BCMathFunctions.java    License: Apache License 2.0 6 votes vote down vote up
public static Memory bcdiv(Environment env, Memory left, Memory right, int scale){
    BigDecimal bd1 = toBigDecimal(left);
    BigDecimal bd2 = toBigDecimal(right);

    if (bd2.compareTo(BigDecimal.ZERO) == 0) {
        return Memory.NULL;
    }

    BigDecimal result;

    if (scale > 0)
        result = bd1.divide(bd2, scale + 2, RoundingMode.DOWN);
    else
        result = bd1.divide(bd2, 2, RoundingMode.DOWN);

    result = result.setScale(scale, RoundingMode.DOWN);
    return new StringMemory(result.toPlainString());
}
 
Example 4
@Override
public final String apply(BigDecimal input) {
    if (input == null) {
        final String nullString = getNullValue().get();
        return nullString != null ? nullString : "null";
    } else {
        return input.toPlainString();
    }
}
 
Example 5
String toText(BigDecimal bigDecimal) {
    if (bigDecimal == null) {
        return "N/A";
    }

    return bigDecimal.toPlainString();
}
 
Example 6
Source Project: mzmine2   File: Precision.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * If the number of digits exceeds maxLength, the format is changed to scientific notation with E
 * as x10
 * 
 * @param value
 * @param sig
 * @param mode
 * @param maxLength maximum length (number of digits)
 * @return A String of the value rounded to sig number of significant digits (figures)
 */
public static String toString(double value, int sig, RoundingMode mode, int maxLength) {
  BigDecimal dec = round(value, sig, mode);
  String str = dec.toPlainString();
  int digits = str.replaceAll("[^0-9]", "").length();
  if (digits <= maxLength)
    return str;
  else {
    format.setMaximumFractionDigits(maxLength - 1);
    return format.format(dec);
  }
}
 
Example 7
Source Project: ET_Redux   File: MathMachine.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param value
 * @return
 */
protected static String formattedValue ( BigDecimal value ) {
    NumberFormat formatter = new DecimalFormat( "0.0000000000E0" );

    String retVal = "";

    if (value.setScale( 0, RoundingMode.DOWN).compareTo( value) == 0){
        retVal = value.toPlainString();
    } else {
        retVal = formatter.format( value.doubleValue() ); //
    }

    return retVal;
}
 
Example 8
public String	getString() {
	BigDecimal localValue = getBigDecimal();
	if (localValue == null)
		return null;
	else
		return localValue.toPlainString();
}
 
Example 9
Source Project: atdl4j   File: SWTNullableSpinner.java    License: MIT License 5 votes vote down vote up
public BigDecimal getValue() 
	{
		if ( ( text.getText()==null ) || ( text.getText().equals("") ) )
		{
			return null;
		}
		else
		{
// note this is what we had to use in SWTSpinnerWidget when getSelection() returned equiv of BigDecimal.unscaledValue()
//	return BigDecimal.valueOf( spinner.getSelection(), spinner.getDigits() );
			BigDecimal tempValue = new BigDecimal( text.getText() );
			BigDecimal tempValueScaled = tempValue.setScale( getDigits(), RoundingMode.HALF_UP );			
			if ( ! tempValue.equals( tempValueScaled ) )
			{
				String tempNewValueString = tempValueScaled.toPlainString();
				logger.debug( "tempValue: " + tempValue + " tempValueScaled: " + tempValueScaled + " tempValueScaled.toPlainString(): " + tempNewValueString );				
				int tempCaretPosition = text.getCaretPosition();
				logger.debug( "getCaretPosition(): " + text.getCaretPosition() );
				// -- Handle user entering ".12" and formatter converting to "0.12" -- avoid result of "0.21") --
				if ( ( tempCaretPosition == 2 ) && 
					  ( text.getText().charAt(0) == '.' ) && 
					  ( tempNewValueString.startsWith( "0." ) ) )
				{
					// -- we're notified at ".1" but formatted value is converting to "0.1" --
					logger.debug("Incrementing CaretPosition (was " + tempCaretPosition + ") to account for formatted string having \".\" converted to \"0.\" automatically." );		
					tempCaretPosition++;
				}
				
				text.setText( tempNewValueString );
				text.setSelection( tempCaretPosition, tempCaretPosition );
			}
			
			return tempValueScaled;
		}
	}
 
Example 10
public static String plainDecimalRepresentation(Number number) {
	double doubleValue = number.doubleValue();
	BigDecimal decimal = BigDecimal.valueOf(doubleValue);
	if (doubleValue >  1.0 || doubleValue < -1.0) {
		DecimalFormat decimalFormat = new DecimalFormat("#0.0");
		return decimalFormat.format(decimal);
	} else {
		return decimal.toPlainString();
	}
}
 
Example 11
private void appendNetDiscountCriterion(Document doc,
        ChargingData chargingData, Element analysisNode) {
    Element netDiscountCriterion = doc
            .createElement(HeidelpayXMLTags.XML_ANALYSIS_CRITERION);
    netDiscountCriterion.setAttribute(HeidelpayXMLTags.XML_ATTRIBUTE_NAME,
            HeidelpayXMLTags.XML_ANALYSIS_AMOUNT_NET_DISCOUNT);
    BigDecimal netDiscount = chargingData.getNetDiscount();
    String netDiscountAsString = netDiscount == null ? "null" : netDiscount
            .toPlainString();
    netDiscountCriterion.setTextContent(netDiscountAsString);
    if (netDiscount != null) {
        analysisNode.appendChild(netDiscountCriterion);
    }
}
 
Example 12
String toText(BigDecimal bigDecimal) {
    if (bigDecimal == null) {
        return "N/A";
    }

    return bigDecimal.toPlainString();
}
 
Example 13
@Override
public int toInt(int index) throws SFException
{
  if (isNull(index))
  {
    return 0;
  }
  BigDecimal bigDecimal = toBigDecimal(index);
  if (bigDecimal.scale() == 0)
  {
    int intValue = bigDecimal.intValue();

    if (bigDecimal.compareTo(BigDecimal.valueOf((long) intValue)) == 0)
    {
      return intValue;
    }
    else
    {
      throw new SFException(ErrorCode.INVALID_VALUE_CONVERT, logicalTypeStr,
                            "Int", bigDecimal.toPlainString());
    }
  }
  else
  {
    throw new SFException(ErrorCode.INVALID_VALUE_CONVERT, logicalTypeStr,
                          "Int", bigDecimal.toPlainString());
  }
}
 
Example 14
private String getValue(final BigDecimal value) {
    return value != null ? value.toPlainString() : "";
}
 
Example 15
public static String _printDecimal(BigDecimal val) {
    return val.toPlainString();
}
 
Example 16
Source Project: simm-lib   File: Sensitivity.java    License: MIT License 4 votes vote down vote up
static Sensitivity curvatureFromVega(Sensitivity vega, SimmConfig config) {
  BigDecimal amount = vega.getAmount();
  BigDecimal amountUsd = vega.getAmountUsd(config.fxRate());
  return new DefaultSensitivity(vega.getProductClass(), vega.getRiskType(), vega.getQualifier(), vega.getBucket(), vega.getLabel1(),
    vega.getLabel2(), amount.toPlainString(), vega.getAmountCurrency(), amountUsd.toPlainString(), SensitivityClass.CURVATURE);
}
 
Example 17
Source Project: DevUtils   File: BigDecimalUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 金额分割, 四舍五入金额
 * @param value       金额数值
 * @param scale       小数点后保留几位
 * @param mode        处理模式
 * @param splitNumber 拆分位数
 * @param splitSymbol 拆分符号
 * @return 指定格式处理的字符串
 */
public static String formatMoney(final BigDecimal value, final int scale, final int mode, final int splitNumber, final String splitSymbol) {
    if (value == null) return null;
    try {
        // 如果等于 0, 直接返回
        if (value.doubleValue() == 0) {
            return value.setScale(scale, mode).toPlainString();
        }
        // 获取原始值字符串 - 非科学计数法
        String valuePlain = value.toPlainString();
        // 判断是否负数
        boolean isNegative = valuePlain.startsWith("-");
        // 处理后的数据
        BigDecimal bigDecimal = new BigDecimal(isNegative ? valuePlain.substring(1) : valuePlain);
        // 范围处理
        valuePlain = bigDecimal.setScale(scale, mode).toPlainString();
        // 进行拆分小数点处理
        String[] values = valuePlain.split("\\.");
        // 判断是否存在小数点
        boolean isDecimal = (values.length == 2);

        // 拼接符号
        String symbol = (splitSymbol != null) ? splitSymbol : "";
        // 防止出现负数
        int number = Math.max(splitNumber, 0);
        // 格式化数据 - 拼接处理
        StringBuilder builder = new StringBuilder();
        // 进行处理小数点前的数值
        for (int len = values[0].length() - 1, i = len, splitPos = 1; i >= 0; i--) {
            // 获取数据
            char ch = values[0].charAt(i);
            builder.append(ch); // 保存数据
            // 判断是否需要追加符号
            if (number > 0 && splitPos % number == 0 && i != 0) {
                builder.append(symbol);
            }
            splitPos++;
        }
        // 倒序处理
        builder.reverse();
        // 存在小数点, 则进行拼接
        if (isDecimal) {
            builder.append(".").append(values[1]);
        }
        // 判断是否负数
        return isNegative ? "-" + builder.toString() : builder.toString();
    } catch (Exception e) {
        JCLogUtils.eTag(TAG, e, "formatMoney");
    }
    return null;
}
 
Example 18
public static String _printDecimal(BigDecimal val) {
    return val.toPlainString();
}
 
Example 19
@TypeConverter
public static String bigDecimal(BigDecimal decimal) {
    return decimal == null ? null : decimal.toPlainString();
}
 
Example 20
Source Project: KantaCDA-API   File: KantaCDAUtil.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Muuntaa desimaaliluvun merkkijonoksi ja poistaa desimaalit, jotka eivät ole merkitseviä. Esim. 4.0 --> 4.
 * 
 * @param luku
 * @return
 */
public static String doubleToString(double luku) {
    BigDecimal bd = BigDecimal.valueOf(luku);
    String bdS = bd.toPlainString();
    return bdS.indexOf(".") < 0 ? bdS : bdS.replaceAll("0*$", "").replaceAll("\\.$", "");
}