Java Message Format formatAsNumber(double value)

Here you can find the source of formatAsNumber(double value)

Description

format As Number

License

Open Source License

Declaration

public static String formatAsNumber(double value) 

Method Source Code

//package com.java2s;
/**// w ww.  j av a  2  s  .co m
 *  
 * Copyright (c) 2015 Fannie Mae, All rights reserved.
 * This program and the accompany materials are made available under
 * the terms of the Fannie Mae Open Source Licensing Project available 
 * at https://github.com/FannieMaeOpenSource/ezPie/wiki/License
 * 
 * ezPIE? is a registered trademark of Fannie Mae
 * 
 */

import java.math.BigDecimal;
import java.text.MessageFormat;

public class Main {
    public static String formatAsNumber(double value) {
        BigDecimal valueOf = BigDecimal.valueOf(value);
        BigDecimal integerPart = BigDecimal.valueOf(valueOf.longValue());
        BigDecimal fractional = valueOf.subtract(integerPart);
        String fraction = fractional.toPlainString();
        int indexOfDot = fraction.indexOf('.') + 1;
        String sign = fraction.startsWith("-") ? "-" : "";
        fraction = fraction.length() > indexOfDot ? fraction.substring(indexOfDot) : fraction;
        if (fraction.equals("0")) {
            return MessageFormat.format("{0}{1}", sign, integerPart.toPlainString(), fraction);
        } else {
            return MessageFormat.format("{0}{1}.{2}", sign, integerPart.toPlainString(), fraction);
        }
    }
}

Related

  1. format(String pattern, Object... args)
  2. format(String pattern, String[] replacements)
  3. format(String str, int replacement)
  4. format(String str, Object... arguments)
  5. format(String textPattern, Object... args)
  6. formatCause(final String message, final Throwable cause, final Object... args)
  7. formatDuring(long mss, String pattern)
  8. formatError(Map.Entry entry, String errorPlural, String errorSingular)
  9. formatMessage(final String pattern, final Object... params)