Java Locale Format formatNumber(Number value, String format)

Here you can find the source of formatNumber(Number value, String format)

Description

Formats an arbitrary numeric object according to the current locale.

License

Apache License

Declaration

public static String formatNumber(Number value, String format) 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.text.DecimalFormat;

import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

public class Main {
    private static Map<String, ThreadLocal<DecimalFormat>> decimalFormatters = new ConcurrentHashMap<String, ThreadLocal<DecimalFormat>>();

    /**//  w w  w  .  j  av  a2 s .com
     *  Formats an arbitrary numeric object according to the current locale.
     *  Relies on auto-boxing for primitives.
     */
    public static String formatNumber(Number value, String format) {
        return getNumberFormatter(format).format(value);
    }

    private static DecimalFormat getNumberFormatter(final String format) {
        ThreadLocal<DecimalFormat> threadLocal = decimalFormatters.get(format);
        if (threadLocal == null) {
            threadLocal = new ThreadLocal<DecimalFormat>() {
                @Override
                protected DecimalFormat initialValue() {
                    return new DecimalFormat(format);
                }
            };
            decimalFormatters.put(format, threadLocal);
        }
        return threadLocal.get();
    }
}

Related

  1. formatNumber(long number)
  2. formatNumber(long value)
  3. formatNumber(Number num)
  4. formatNumber(Number number)
  5. formatNumber(Number value, int minDecimals, int maxDecimals, boolean grouping, boolean dotDecimalSymbol)
  6. formatNumber(Object number, String pattern, Locale locale)
  7. formatNumber(Object value, Locale locale)
  8. formatNumber(Object value, String numberFormat)
  9. formatNumberSameWidth(final double v)