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

The following examples show how to use java.math.BigDecimal#toPlainString() . 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: DatatypeRulesTestLanguageValueConverters.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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
Source File: BCMathFunctions.java    From jphp with 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 3
Source File: ValueTypeToStringConverter.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@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 4
Source File: PrinterOfBigDecimal.java    From morpheus-core with Apache License 2.0 5 votes vote down vote up
@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
Source File: ListAdapter.java    From Building-Professional-Android-Applications with MIT License 5 votes vote down vote up
String toText(BigDecimal bigDecimal) {
    if (bigDecimal == null) {
        return "N/A";
    }

    return bigDecimal.toPlainString();
}
 
Example 6
Source File: Precision.java    From mzmine2 with 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 File: MathMachine.java    From ET_Redux with 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
Source File: DecimalToScaledFixedConverter.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
@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 9
Source File: SQLDecimal.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
public String	getString() {
	BigDecimal localValue = getBigDecimal();
	if (localValue == null)
		return null;
	else
		return localValue.toPlainString();
}
 
Example 10
Source File: SWTNullableSpinner.java    From atdl4j with 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 11
Source File: StringLibrary.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
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 12
Source File: PaymentServiceProviderBean.java    From development with Apache License 2.0 5 votes vote down vote up
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 13
Source File: ListAdapter.java    From Building-Professional-Android-Applications with MIT License 5 votes vote down vote up
String toText(BigDecimal bigDecimal) {
    if (bigDecimal == null) {
        return "N/A";
    }

    return bigDecimal.toPlainString();
}
 
Example 14
Source File: Converters.java    From Building-Professional-Android-Applications with MIT License 4 votes vote down vote up
@TypeConverter
public static String bigDecimal(BigDecimal decimal) {
    return decimal == null ? null : decimal.toPlainString();
}
 
Example 15
Source File: DatatypeConverterImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static String _printDecimal(BigDecimal val) {
    return val.toPlainString();
}
 
Example 16
Source File: BigDecimalUtils.java    From DevUtils with 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 17
Source File: Sensitivity.java    From simm-lib with 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 18
Source File: DatatypeConverterImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static String _printDecimal(BigDecimal val) {
    return val.toPlainString();
}
 
Example 19
Source File: DegreeTransferCandidacyProcessDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
private String getValue(final BigDecimal value) {
    return value != null ? value.toPlainString() : "";
}
 
Example 20
Source File: KantaCDAUtil.java    From KantaCDA-API with 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("\\.$", "");
}