Example usage for java.text NumberFormat getNumberInstance

List of usage examples for java.text NumberFormat getNumberInstance

Introduction

In this page you can find the example usage for java.text NumberFormat getNumberInstance.

Prototype

public static NumberFormat getNumberInstance(Locale inLocale) 

Source Link

Document

Returns a general-purpose number format for the specified locale.

Usage

From source file:com.ultrapower.eoms.common.plugin.ecside.util.ExtremeUtils.java

    public static String formatNumber(String format, Object value, Locale locale) {
        String result = null;/*from   ww w  . ja  v a2 s .  c om*/

        if (value == null) {
            return result;
        }

        if (StringUtils.isBlank(format)) {
//            logger.warn("The format was not defined for number [" + value.toString() + "].");
            return value.toString();
        }

        NumberFormat nf = NumberFormat.getNumberInstance(locale);
        DecimalFormat df = (DecimalFormat) nf;
        df.applyLocalizedPattern(format);

        return df.format(Double.parseDouble(value.toString()));
    }

From source file:org.openestate.io.core.NumberUtils.java

/**
 * Convert a string value into a number.
 *
 * @param value//from   w w w  .  ja va2s  .  c  o  m
 * the string value to convert
 *
 * @param integerOnly
 * wether only the integer part of the value is parsed
 *
 * @param locales
 * locales, against which the value is parsed
 *
 * @return
 * numeric value for the string
 *
 * @throws NumberFormatException
 * if the string is not a valid number
 */
public static Number parseNumber(String value, boolean integerOnly, Locale... locales)
        throws NumberFormatException {
    value = StringUtils.trimToNull(value);
    if (value == null)
        return null;

    // ignore leading plus sign
    if (value.startsWith("+"))
        value = StringUtils.trimToNull(value.substring(1));

    // remove any spaces
    value = StringUtils.replace(value, StringUtils.SPACE, StringUtils.EMPTY);

    if (ArrayUtils.isEmpty(locales))
        locales = new Locale[] { Locale.getDefault() };

    for (Locale locale : locales) {
        // check, if the value is completely numeric for the locale
        if (!isNumeric(value, locale))
            continue;
        try {
            NumberFormat format = NumberFormat.getNumberInstance(locale);
            format.setMinimumFractionDigits(0);
            format.setGroupingUsed(false);
            format.setParseIntegerOnly(integerOnly);
            return format.parse(value);
        } catch (ParseException ex) {
        }
    }
    throw new NumberFormatException("The provided value '" + value + "' is not numeric!");
}

From source file:com.googlecode.jtiger.modules.ecside.util.ExtremeUtils.java

public static String formatNumber(String format, Object value, Locale locale) {
    String result = null;/*from w  ww.j  ava 2  s .  co m*/

    if (value == null) {
        return result;
    }

    if (StringUtils.isBlank(format)) {
        //            logger.warn("The format was not defined for number [" + value.toString() + "].");
        return value.toString();
    }

    NumberFormat nf = NumberFormat.getNumberInstance(locale);
    DecimalFormat df = (DecimalFormat) nf;
    df.applyLocalizedPattern(format);

    return df.format(Double.parseDouble(value.toString()));
}

From source file:easyJ.common.validate.GenericTypeValidator.java

/**
 * Checks if the value can safely be converted to a short primitive.
 * /*w  w w .  ja v a  2  s  . co m*/
 * @param value
 *                The value validation is being performed on.
 * @param locale
 *                The locale to use to parse the number (system default if
 *                null)vv
 * @return the converted Short value.
 */
public static Short formatShort(String value, Locale locale) {
    Short result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Short.MIN_VALUE && num.doubleValue() <= Short.MAX_VALUE) {
                result = new Short(num.shortValue());
            }
        }
    }

    return result;
}

From source file:org.evosuite.continuous.persistency.StorageManager.java

public StorageManager() {
    this.isStorageOk = this.openForWriting();
    this.df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.ENGLISH);
    this.df.applyPattern("#0.00");
}

From source file:org.projectforge.web.statistics.PersonalStatisticsPage.java

public PersonalStatisticsPage(final PageParameters parameters) {
    super(parameters);
    final Label timesheetDisciplineChartTitle = new Label("timesheetDisciplineChartTitle",
            getString("personal.statistics.timesheetDisciplineChart.title"));
    body.add(timesheetDisciplineChartTitle);
    final Shape shape = new Ellipse2D.Float(-3, -3, 6, 6);
    // final Shape shape = null;
    final Stroke stroke = new BasicStroke(3.0f);
    // final Stroke stroke = new BasicStroke(1.0f);
    final EmployeeDO employee = employeeDao.getByUserId(PFUserContext.getUserId());
    double workingHoursPerDay = 8;
    if (employee != null && NumberHelper.greaterZero(employee.getWochenstunden()) == true) {
        workingHoursPerDay = employee.getWochenstunden() / 5;
    }//from   ww  w.  j  av  a  2 s.  com
    final TimesheetDisciplineChartBuilder chartBuilder = new TimesheetDisciplineChartBuilder();
    final JFreeChart chart1 = chartBuilder.create(timesheetDao, getUser().getId(), workingHoursPerDay,
            LAST_N_DAYS, shape, stroke, true);
    JFreeChartImage image = new JFreeChartImage("timesheetStatisticsImage1", chart1, IMAGE_WIDTH, IMAGE_HEIGHT);
    image.add(AttributeModifier.replace("width", String.valueOf(IMAGE_WIDTH)));
    image.add(AttributeModifier.replace("height", String.valueOf(IMAGE_HEIGHT)));
    body.add(image);
    final NumberFormat format = NumberFormat.getNumberInstance(PFUserContext.getLocale());
    final String planHours = "<span style=\"color: #DE1821; font-weight: bold;\">"
            + format.format(chartBuilder.getPlanWorkingHours()) + "</span>";
    final String actualHours = "<span style=\"color: #40A93B; font-weight: bold;\">"
            + format.format(chartBuilder.getActualWorkingHours()) + "</span>";
    final String numberOfDays = String.valueOf(LAST_N_DAYS);
    final Label timesheetDisciplineChart1Legend = new Label("timesheetDisciplineChart1Legend",
            getLocalizedMessage("personal.statistics.timesheetDisciplineChart1.legend", numberOfDays, planHours,
                    actualHours));
    timesheetDisciplineChart1Legend.setEscapeModelStrings(false);
    body.add(timesheetDisciplineChart1Legend);

    final JFreeChart chart2 = chartBuilder.create(timesheetDao, getUser().getId(), LAST_N_DAYS, shape, stroke,
            true);
    image = new JFreeChartImage("timesheetStatisticsImage2", chart2, IMAGE_WIDTH, IMAGE_HEIGHT);
    image.add(AttributeModifier.replace("width", String.valueOf(IMAGE_WIDTH)));
    image.add(AttributeModifier.replace("height", String.valueOf(IMAGE_HEIGHT)));
    body.add(image);
    final String averageDifference = "<span style=\"color: #DE1821; font-weight: bold;\">"
            + format.format(chartBuilder.getAverageDifferenceBetweenTimesheetAndBooking()) + "</span>";
    final String plannedDifference = "<span style=\"color: #40A93B; font-weight: bold;\">"
            + format.format(chartBuilder.getPlannedAverageDifferenceBetweenTimesheetAndBooking()) + "</span>";
    final Label timesheetDisciplineChart2Legend = new Label("timesheetDisciplineChart2Legend",
            getLocalizedMessage("personal.statistics.timesheetDisciplineChart2.legend", numberOfDays,
                    plannedDifference, averageDifference));
    timesheetDisciplineChart2Legend.setEscapeModelStrings(false);
    body.add(timesheetDisciplineChart2Legend);
}

From source file:org.sakaiproject.tool.assessment.jsf.validator.FinQuestionValidator.java

static boolean isComplexNumber(String value) {

    boolean isComplex = true;
    Complex complex = null;//from  www  . ja  va 2s  .  co m
    try {
        DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
        df.setGroupingUsed(false);

        // Numerical format ###.## (decimal symbol is the point)
        ComplexFormat complexFormat = new ComplexFormat(df);
        complex = complexFormat.parse(value);

        // This is because there is a bug parsing complex number. 9i is parsed as 9
        if (complex.getImaginary() == 0 && value.contains("i"))
            isComplex = false;
    } catch (Exception e) {
        isComplex = false;
    }

    return isComplex;
}

From source file:org.lingcloud.molva.ocl.util.GenericTypeValidator.java

/**
 * Checks if the value can safely be converted to a short primitive.
 * /*w  ww.  j  a v a 2  s  .c  o m*/
 * @param value
 *            The value validation is being performed on.
 * @param locale
 *            The locale to use to parse the number (system default if
 *            null)vv
 * @return the converted Short value.
 */
public static Short formatShort(String value, Locale locale) {
    Short result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Short.MIN_VALUE && num.doubleValue() <= Short.MAX_VALUE) {
                result = Short.valueOf(num.shortValue());
            }
        }
    }

    return result;
}

From source file:moe.encode.airblock.commands.arguments.types.PrimitiveParser.java

@Override
public Object convert(Executor executor, ArgumentConverter parser, Type type, String value) {
    Class<?> cls = ReflectionUtils.toClass(type);
    if (ClassUtils.isPrimitiveWrapper(cls))
        cls = ClassUtils.wrapperToPrimitive(cls);

    if (cls.equals(boolean.class))
        return this.isTrue(executor, value);
    else if (cls.equals(char.class)) {
        if (value.length() > 0)
            throw new NumberFormatException("Character arguments cannot be longer than one characters");
        return value.charAt(0);
    }/*from w ww.  jav a2 s. c o m*/

    // Get the locale of the user and get a number-format according to it.
    LocaleResolver resolver = TranslationManager.getResolver(executor);
    Locale locale;
    if (resolver != null)
        locale = resolver.getLocale();
    else
        locale = Locale.ENGLISH;

    NumberFormat nf = NumberFormat.getNumberInstance(locale);
    nf.setGroupingUsed(true);

    // Parse the value.
    Number result;
    try {
        result = nf.parse(value);
    } catch (ParseException e) {
        NumberFormatException nfe = new NumberFormatException("Invalid number");
        nfe.initCause(e);
        throw nfe;
    }

    // Returns the value in the correct type.
    if (cls.equals(int.class))
        return result.intValue();
    else if (cls.equals(float.class))
        return result.floatValue();
    else if (cls.equals(double.class))
        return result.doubleValue();
    else if (cls.equals(byte.class))
        return result.byteValue();
    else if (cls.equals(short.class))
        return result.shortValue();
    else if (cls.equals(long.class))
        return result.longValue();

    throw new NumberFormatException("Unknown primitive type.");
}

From source file:org.extremecomponents.util.ExtremeUtils.java

/**
 * //from  w  w  w.  j  ava  2 s .c o m
 * @param format
 * @param value
 * @return
 */
public static String formatNumber(String format, Object value, Locale locale) {
    String result = null;

    if (value == null) {
        return result;
    }

    if (StringUtils.isBlank(format)) {
        logger.error("The format was not defined for number [" + value.toString() + "].");
        return value.toString();
    }

    NumberFormat nf = NumberFormat.getNumberInstance(locale);
    DecimalFormat df = (DecimalFormat) nf;
    df.applyLocalizedPattern(format);

    return df.format(Double.parseDouble(value.toString()));
}