Java BigDecimal currencyFormat(BigDecimal value, char decimalDelimiter)

Here you can find the source of currencyFormat(BigDecimal value, char decimalDelimiter)

Description

currency Format

License

Open Source License

Declaration

public static String currencyFormat(BigDecimal value, char decimalDelimiter) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.math.BigDecimal;

public class Main {
    public static String currencyFormat(BigDecimal value, char decimalDelimiter) {
        /*/*from   ww w  .j a v a 2s. c o  m*/
         *I needed 123,45, locale independent. 
         *I tried NumberFormat.getCurrencyInstance().format( 12345.6789 ); but that is locale specific.
         *I also tried 
        DecimalFormat df = new DecimalFormat( "0,00" );
        df.setDecimalSeparatorAlwaysShown(true);
        df.setGroupingUsed(false);
        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        symbols.setDecimalSeparator(',');
        symbols.setGroupingSeparator(' ');
        df.setDecimalFormatSymbols(symbols);
            
        but that would not switch off grouping. 
        Although I liked very much the (incomplete) "BNF diagram" in http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
        in the end I decided to calculate myself and take eur+sparator+cents
            
        This function will cut off, i.e. floor() subcent values
        Tests:
        System.err.println(utils.currencyFormat(new BigDecimal(0), ".")+"\n"+utils.currencyFormat(new BigDecimal("-1.10"), ",")+"\n"+utils.currencyFormat(new BigDecimal("-1.1"), ",")+"\n"+utils.currencyFormat(new BigDecimal("-1.01"), ",")+"\n"+utils.currencyFormat(new BigDecimal("20000123.3489"), ",")+"\n"+utils.currencyFormat(new BigDecimal("20000123.3419"), ",")+"\n"+utils.currencyFormat(new BigDecimal("12"), ","));
            
        results
        0.00
        -1,10
        -1,10
        -1,01
        20000123,34
        20000123,34
        12,00
            
        */
        long totalCent = value.multiply(new BigDecimal(100)).intValue();
        long eurOnly = value.longValue();
        long centOnly = Math.abs(totalCent % 100);
        StringBuffer res = new StringBuffer();
        res.append(eurOnly);
        res.append(decimalDelimiter);
        if (centOnly < 10) {
            res.append('0');
        }
        res.append(centOnly);
        return res.toString();
    }
}

Related

  1. byteOverflow(BigDecimal value)
  2. cloneBigDecimal(BigDecimal bdOriginal)
  3. createJsonNumber(BigDecimal d)
  4. createReconFileHeader(int totalCount, BigDecimal totalAmount)
  5. cuberoot(BigDecimal b)
  6. decimalDigits(BigDecimal d)
  7. deserializeBigDecimalFromString(String decimal)
  8. exp(BigDecimal power)
  9. exp(BigDecimal x, int scale)