Java Examples for java.text.DecimalFormatSymbols

The following java examples will help you to understand the usage of java.text.DecimalFormatSymbols. These source code samples are taken from different open source projects.

Example 1
Project: android-sdk-sources-for-api-level-23-master  File: DecimalFormatSymbolsTest.java View source code
/**
     * @tests java.text.DecimalFormatSymbols#getAvailableLocales()
     */
public void test_getAvailableLocales_no_provider() throws Exception {
    Locale[] locales = DecimalFormatSymbols.getAvailableLocales();
    assertNotNull(locales);
    // must contain Locale.US
    boolean flag = false;
    for (Locale locale : locales) {
        if (locale.equals(Locale.US)) {
            flag = true;
            break;
        }
    }
    assertTrue(flag);
}
Example 2
Project: ARTPart-master  File: DecimalFormatSymbolsTest.java View source code
public void test_getInstance_unknown_or_invalid_locale() throws Exception {
    // http://b/17374604: this test passes on the host but fails on the target.
    // ICU uses setlocale(3) to determine its default locale, and glibc (on my box at least)
    // returns "en_US.UTF-8". bionic before L returned NULL and in L returns "C.UTF-8", both
    // of which get treated as "en_US_POSIX". What that means for this test is that you get
    // "INF" for infinity instead of "\u221e".
    // On the RI, this test fails for a different reason: their DecimalFormatSymbols.equals
    // appears to be broken. It could be that they're accidentally checking the Locale field?
    checkLocaleIsEquivalentToRoot(new Locale("xx", "XX"));
    checkLocaleIsEquivalentToRoot(new Locale("not exist language", "not exist country"));
}
Example 3
Project: j2objc-master  File: FuncFormatNumb.java View source code
/**
   * Execute the function.  The function must return
   * a valid object.
   * @param xctxt The current execution context.
   * @return A valid XObject.
   *
   * @throws javax.xml.transform.TransformerException
   */
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException {
    // A bit of an ugly hack to get our context.
    ElemTemplateElement templElem = (ElemTemplateElement) xctxt.getNamespaceContext();
    StylesheetRoot ss = templElem.getStylesheetRoot();
    java.text.DecimalFormat formatter = null;
    java.text.DecimalFormatSymbols dfs = null;
    double num = getArg0().execute(xctxt).num();
    String patternStr = getArg1().execute(xctxt).str();
    // TODO: what should be the behavior here??
    if (patternStr.indexOf(0x00A4) > 0)
        // currency sign not allowed
        ss.error(XSLTErrorResources.ER_CURRENCY_SIGN_ILLEGAL);
    // decimal-format declared in the stylesheet!(xsl:decimal-format
    try {
        Expression arg2Expr = getArg2();
        if (null != arg2Expr) {
            String dfName = arg2Expr.execute(xctxt).str();
            QName qname = new QName(dfName, xctxt.getNamespaceContext());
            dfs = ss.getDecimalFormatComposed(qname);
            if (null == dfs) {
                warn(xctxt, XSLTErrorResources.WG_NO_DECIMALFORMAT_DECLARATION, //"not found!!!
                new Object[] { dfName });
            //formatter = new java.text.DecimalFormat(patternStr);
            } else {
                //formatter = new java.text.DecimalFormat(patternStr, dfs);
                formatter = new java.text.DecimalFormat();
                formatter.setDecimalFormatSymbols(dfs);
                formatter.applyLocalizedPattern(patternStr);
            }
        }
        //else
        if (null == formatter) {
            // look for a possible default decimal-format
            dfs = ss.getDecimalFormatComposed(new QName(""));
            if (dfs != null) {
                formatter = new java.text.DecimalFormat();
                formatter.setDecimalFormatSymbols(dfs);
                formatter.applyLocalizedPattern(patternStr);
            } else {
                dfs = new java.text.DecimalFormatSymbols(java.util.Locale.US);
                dfs.setInfinity(Constants.ATTRVAL_INFINITY);
                dfs.setNaN(Constants.ATTRVAL_NAN);
                formatter = new java.text.DecimalFormat();
                formatter.setDecimalFormatSymbols(dfs);
                if (null != patternStr)
                    formatter.applyLocalizedPattern(patternStr);
            }
        }
        return new XString(formatter.format(num));
    } catch (Exception iae) {
        templElem.error(XSLTErrorResources.ER_MALFORMED_FORMAT_STRING, new Object[] { patternStr });
        return XString.EMPTYSTRING;
    }
}
Example 4
Project: android_libcore-master  File: FuncFormatNumb.java View source code
/**
   * Execute the function.  The function must return
   * a valid object.
   * @param xctxt The current execution context.
   * @return A valid XObject.
   *
   * @throws javax.xml.transform.TransformerException
   */
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException {
    // A bit of an ugly hack to get our context.
    ElemTemplateElement templElem = (ElemTemplateElement) xctxt.getNamespaceContext();
    StylesheetRoot ss = templElem.getStylesheetRoot();
    java.text.DecimalFormat formatter = null;
    java.text.DecimalFormatSymbols dfs = null;
    double num = getArg0().execute(xctxt).num();
    String patternStr = getArg1().execute(xctxt).str();
    // TODO: what should be the behavior here??
    if (patternStr.indexOf(0x00A4) > 0)
        // currency sign not allowed
        ss.error(XSLTErrorResources.ER_CURRENCY_SIGN_ILLEGAL);
    // decimal-format declared in the stylesheet!(xsl:decimal-format
    try {
        Expression arg2Expr = getArg2();
        if (null != arg2Expr) {
            String dfName = arg2Expr.execute(xctxt).str();
            QName qname = new QName(dfName, xctxt.getNamespaceContext());
            dfs = ss.getDecimalFormatComposed(qname);
            if (null == dfs) {
                warn(xctxt, XSLTErrorResources.WG_NO_DECIMALFORMAT_DECLARATION, //"not found!!!
                new Object[] { dfName });
            //formatter = new java.text.DecimalFormat(patternStr);
            } else {
                //formatter = new java.text.DecimalFormat(patternStr, dfs);
                formatter = new java.text.DecimalFormat();
                formatter.setDecimalFormatSymbols(dfs);
                formatter.applyLocalizedPattern(patternStr);
            }
        }
        //else
        if (null == formatter) {
            // look for a possible default decimal-format
            dfs = ss.getDecimalFormatComposed(new QName(""));
            if (dfs != null) {
                formatter = new java.text.DecimalFormat();
                formatter.setDecimalFormatSymbols(dfs);
                formatter.applyLocalizedPattern(patternStr);
            } else {
                dfs = new java.text.DecimalFormatSymbols(java.util.Locale.US);
                dfs.setInfinity(Constants.ATTRVAL_INFINITY);
                dfs.setNaN(Constants.ATTRVAL_NAN);
                formatter = new java.text.DecimalFormat();
                formatter.setDecimalFormatSymbols(dfs);
                if (null != patternStr)
                    formatter.applyLocalizedPattern(patternStr);
            }
        }
        return new XString(formatter.format(num));
    } catch (Exception iae) {
        templElem.error(XSLTErrorResources.ER_MALFORMED_FORMAT_STRING, new Object[] { patternStr });
        return XString.EMPTYSTRING;
    }
}
Example 5
Project: open-mika-master  File: topattern.java View source code
public void test(TestHarness harness) {
    // Just to be explicit: we're only testing the US locale here.
    Locale loc = Locale.US;
    Locale.setDefault(loc);
    // There aren't really many tests we can do, since it doesn't
    // seem like any canonical output format is documented.
    DecimalFormat df = new DecimalFormat("0.##");
    harness.check(df.toPattern(), "0.##");
    harness.check(df.toLocalizedPattern(), "0.##");
    DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
    dfs.setDecimalSeparator(',');
    dfs.setZeroDigit('1');
    dfs.setDigit('X');
    dfs.setGroupingSeparator('!');
    harness.check(df.toLocalizedPattern(), "1,XX");
    df.applyPattern("Fr #,##0.##");
    String x1 = df.toPattern();
    String x2 = df.toLocalizedPattern();
    harness.check(x1.length(), x2.length());
    boolean ok = x1.length() == x2.length();
    for (int i = 0; i < x1.length(); ++i) {
        char c = x1.charAt(i);
        if (c == '0')
            c = '1';
        else if (c == '#')
            c = 'X';
        else if (c == '.')
            c = ',';
        else if (c == ',')
            c = '!';
        if (c != x2.charAt(i)) {
            ok = false;
            harness.debug("failure at char " + i);
            harness.debug("x1 = " + x1 + "\nx2 = " + x2);
            break;
        }
    }
    harness.check(ok);
}
Example 6
Project: xstream-for-android-master  File: XmlFriendlyTest.java View source code
public void testDecimalFormatSymbols() {
    final String xml;
    if (!JVM.is14()) {
        xml = "<java.text.DecimalFormatSymbols serialization=\"custom\">\n" + "  <java.text.DecimalFormatSymbols>\n" + "    <default>\n" + "      <decimalSeparator>,</decimalSeparator>\n" + "      <digit>#</digit>\n" + "      <exponential>E</exponential>\n" + "      <groupingSeparator>.</groupingSeparator>\n" + "      <minusSign>-</minusSign>\n" + "      <monetarySeparator>,</monetarySeparator>\n" + "      <patternSeparator>;</patternSeparator>\n" + "      <perMill>‰</perMill>\n" + "      <percent>%</percent>\n" + "      <serialVersionOnStream>1</serialVersionOnStream>\n" + "      <zeroDigit>0</zeroDigit>\n" + "      <NaN>�</NaN>\n" + "      <currencySymbol>DM</currencySymbol>\n" + "      <infinity>∞</infinity>\n" + "      <intlCurrencySymbol>DEM</intlCurrencySymbol>\n" + "    </default>\n" + "  </java.text.DecimalFormatSymbols>\n" + "</java.text.DecimalFormatSymbols>";
    } else if (!JVM.is16()) {
        xml = "<java.text.DecimalFormatSymbols serialization=\"custom\">\n" + "  <java.text.DecimalFormatSymbols>\n" + "    <default>\n" + "      <decimalSeparator>,</decimalSeparator>\n" + "      <digit>#</digit>\n" + "      <exponential>E</exponential>\n" + "      <groupingSeparator>.</groupingSeparator>\n" + "      <minusSign>-</minusSign>\n" + "      <monetarySeparator>,</monetarySeparator>\n" + "      <patternSeparator>;</patternSeparator>\n" + "      <perMill>‰</perMill>\n" + "      <percent>%</percent>\n" + "      <serialVersionOnStream>2</serialVersionOnStream>\n" + "      <zeroDigit>0</zeroDigit>\n" + "      <NaN>�</NaN>\n" + "      <currencySymbol>€</currencySymbol>\n" + "      <infinity>∞</infinity>\n" + "      <intlCurrencySymbol>EUR</intlCurrencySymbol>\n" + "      <locale>de_DE</locale>\n" + "    </default>\n" + "  </java.text.DecimalFormatSymbols>\n" + "</java.text.DecimalFormatSymbols>";
    } else {
        xml = "<java.text.DecimalFormatSymbols serialization=\"custom\">\n" + "  <java.text.DecimalFormatSymbols>\n" + "    <default>\n" + "      <decimalSeparator>,</decimalSeparator>\n" + "      <digit>#</digit>\n" + "      <exponential>E</exponential>\n" + "      <groupingSeparator>.</groupingSeparator>\n" + "      <minusSign>-</minusSign>\n" + "      <monetarySeparator>,</monetarySeparator>\n" + "      <patternSeparator>;</patternSeparator>\n" + "      <perMill>‰</perMill>\n" + "      <percent>%</percent>\n" + "      <serialVersionOnStream>3</serialVersionOnStream>\n" + "      <zeroDigit>0</zeroDigit>\n" + "      <NaN>�</NaN>\n" + "      <currencySymbol>€</currencySymbol>\n" + "      <exponentialSeparator>E</exponentialSeparator>\n" + "      <infinity>∞</infinity>\n" + "      <intlCurrencySymbol>EUR</intlCurrencySymbol>\n" + "      <locale>de_DE</locale>\n" + "    </default>\n" + "  </java.text.DecimalFormatSymbols>\n" + "</java.text.DecimalFormatSymbols>";
    }
    final DecimalFormatSymbols format = new DecimalFormatSymbols(Locale.GERMANY);
    assertBothWays(format, xml);
}
Example 7
Project: thunderstorm-master  File: StringFormatting.java View source code
public static DecimalFormat getDecimalFormat(int floatPrecision) {
    DecimalFormat df = new DecimalFormat();
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.US);
    symbols.setInfinity("Infinity");
    symbols.setNaN("NaN");
    df.setDecimalFormatSymbols(symbols);
    df.setGroupingUsed(false);
    df.setRoundingMode(RoundingMode.HALF_EVEN);
    df.setMaximumFractionDigits(floatPrecision);
    return df;
}
Example 8
Project: ssie-versioned-master  File: EasyFormat.java View source code
public static DecimalFormat getStdFormat() {
    if (stdFormat == null) {
        DecimalFormatSymbols dsymb = new DecimalFormatSymbols();
        // on french locales, dots print like comma
        dsymb.setDecimalSeparator('.');
        stdFormat = new DecimalFormat("0.0000");
        stdFormat.setDecimalFormatSymbols(dsymb);
    }
    return stdFormat;
}
Example 9
Project: android-libcore64-master  File: NumberFormatTest.java View source code
public void test_numberLocalization() throws Exception {
    Locale arabic = new Locale("ar");
    if (!Support_Locale.isLocaleAvailable(arabic)) {
        return;
    }
    NumberFormat nf = NumberFormat.getNumberInstance(arabic);
    assertEquals('٠', new DecimalFormatSymbols(arabic).getZeroDigit());
    assertEquals("١٢٣٤٥٦٧٨٩٠", nf.format(1234567890));
}
Example 10
Project: android_platform_libcore-master  File: NumberFormatTest.java View source code
public void test_numberLocalization() throws Exception {
    Locale arabic = new Locale("ar");
    if (!Support_Locale.isLocaleAvailable(arabic)) {
        return;
    }
    NumberFormat nf = NumberFormat.getNumberInstance(arabic);
    assertEquals('٠', new DecimalFormatSymbols(arabic).getZeroDigit());
    assertEquals("١٬٢٣٤٬٥٦٧٬٨٩٠", nf.format(1234567890));
}
Example 11
Project: dynjs-master  File: ToExponential.java View source code
@Override
public Object call(ExecutionContext context, Object self, Object... args) {
    // 15.7.4.6 Number.prototype.toExponential (fractionDigits)
    Number number = Types.toNumber(context, self);
    Long fractionDigits = Types.toInteger(context, args[0]);
    if (Double.isNaN(number.doubleValue()) || Double.isInfinite(number.doubleValue())) {
        return String.valueOf(number);
    }
    if (fractionDigits < 0 || fractionDigits > 20) {
        throw new ThrowException(context, context.createRangeError("Number.prototype.toExponential() [fractionDigits] must be between 0 and 20"));
    }
    DecimalFormat decimalFormat = new DecimalFormat("0.00##################E0");
    decimalFormat.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    decimalFormat.setMinimumFractionDigits(fractionDigits.intValue());
    return Types.rewritePossiblyExponentialValue(decimalFormat.format(number.doubleValue()));
}
Example 12
Project: geotools-tike-master  File: NumberFormatTest.java View source code
public void testFormatDouble() {
    FilterFactory ff = CommonFactoryFinder.getFilterFactory(null);
    Literal pattern = ff.literal("#.##");
    Literal number = ff.literal("10.56789");
    Function f = ff.function("numberFormat", new Expression[] { pattern, number });
    char ds = new DecimalFormatSymbols().getDecimalSeparator();
    assertEquals("10" + ds + "57", f.evaluate(null, String.class));
}
Example 13
Project: OG-Platform-master  File: DoubleValueDecimalPlaceFormatterTest.java View source code
@Test
public void testLocale() {
    DoubleValueDecimalPlaceFormatter formatter = new DoubleValueDecimalPlaceFormatter(2, false, DecimalFormatSymbols.getInstance(Locale.GERMAN));
    assertEquals("1.234.567,98", format(formatter, 1234567.98));
    assertEquals("1.234.567,00", format(formatter, 1234567));
    assertEquals("1,23", format(formatter, 1.22666));
    formatter = new DoubleValueDecimalPlaceFormatter(2, false, DecimalFormatSymbols.getInstance(Locale.FRENCH));
    String nbsp = " ";
    assertEquals("1" + nbsp + "234,99", format(formatter, 1234.987654321));
}
Example 14
Project: openjump-core-rels-master  File: NumberInputDocument.java View source code
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    char decimalSeparator = dfs.getDecimalSeparator();
    String clearedStr = str.substring(0);
    if (this.getText(0, this.getLength()).indexOf('.') > -1) {
        clearedStr = clearedStr.replaceAll("[^0-9-]", "");
    } else if (decimalSeparator != '.' && this.getText(0, this.getLength()).indexOf(decimalSeparator) > -1) {
        clearedStr = clearedStr.replaceAll("[^0-9-]", "");
    } else {
        clearedStr = clearedStr.replaceAll("[^0-9-." + decimalSeparator + "]", "");
    }
    if (clearedStr.length() > 0) {
        super.insertString(offs, clearedStr, a);
    }
}
Example 15
Project: robovm-master  File: DecimalFormatSymbolsTest.java View source code
public void test_getInstance_unknown_or_invalid_locale() throws Exception {
    // TODO: we fail these tests because ROOT has "INF" for infinity but 'dfs' has "\u221e".
    // On the RI, ROOT has "\u221e" too, but DecimalFormatSymbols.equals appears to be broken;
    // it returns false for objects that -- if you compare their externally visible state --
    // are equal. It could be that they're accidentally checking the Locale.
    checkLocaleIsEquivalentToRoot(new Locale("xx", "XX"));
    checkLocaleIsEquivalentToRoot(new Locale("not exist language", "not exist country"));
}
Example 16
Project: vraptor-i18n-master  File: LocalizedNumber.java View source code
public LocalizedNumber custom(String name) {
    String key = "formats.number." + name;
    String pattern = bundle.getString(key);
    if (String.format("???%s???", name).equals(pattern)) {
        throw new IllegalArgumentException("Custom formatter " + key + " does not exist in your resource bundle.");
    } else {
        this.formatter = new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(locale));
        return this;
    }
}
Example 17
Project: aether-ant-master  File: AntTransferListener.java View source code
@Override
public void transferSucceeded(TransferEvent event) {
    String msg = event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded";
    msg += " " + event.getResource().getRepositoryUrl() + event.getResource().getResourceName();
    long contentLength = event.getTransferredBytes();
    if (contentLength >= 0) {
        String len = contentLength >= 1024 ? ((contentLength + 1023) / 1024) + " KB" : contentLength + " B";
        String throughput = "";
        long duration = System.currentTimeMillis() - event.getResource().getTransferStartTime();
        if (duration > 0) {
            DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH));
            double kbPerSec = (contentLength / 1024.0) / (duration / 1000.0);
            throughput = " at " + format.format(kbPerSec) + " KB/sec";
        }
        msg += " (" + len + throughput + ")";
    }
    task.log(msg);
}
Example 18
Project: android_packages_apps_Calculator-master  File: Constants.java View source code
/**
     * If the locale changes, but the app is still in memory, you may need to rebuild these constants
     * */
public static void rebuildConstants() {
    DECIMAL_FORMAT = new DecimalFormatSymbols();
    // These will already be known by Java
    DECIMAL_POINT = DECIMAL_FORMAT.getDecimalSeparator();
    DECIMAL_SEPARATOR = DECIMAL_FORMAT.getGroupingSeparator();
    // Use a space for Bin and Hex
    BINARY_SEPARATOR = ' ';
    HEXADECIMAL_SEPARATOR = ' ';
    // It defaults to "," but that's a common decimal point.
    if (DECIMAL_POINT == ',')
        MATRIX_SEPARATOR = ' ';
    else
        MATRIX_SEPARATOR = ',';
    String number = "A-F0-9" + Pattern.quote(String.valueOf(DECIMAL_POINT)) + Pattern.quote(String.valueOf(DECIMAL_SEPARATOR)) + Pattern.quote(String.valueOf(BINARY_SEPARATOR)) + Pattern.quote(String.valueOf(HEXADECIMAL_SEPARATOR));
    REGEX_NUMBER = "[" + number + "]";
    REGEX_NOT_NUMBER = "[^" + number + "]";
}
Example 19
Project: beast2-master  File: OutputUtils.java View source code
public static String format(Double d) {
    if (Double.isNaN(d)) {
        return "NaN     ";
    }
    if (Math.abs(d) > 1e-4 || d == 0) {
        DecimalFormat f = new DecimalFormat("#0.######", new DecimalFormatSymbols(Locale.US));
        String str = f.format(d);
        if (str.length() > 8) {
            str = str.substring(0, 8);
        }
        while (str.length() < 8) {
            str += " ";
        }
        return str;
    } else {
        DecimalFormat f = new DecimalFormat("0.##E0", new DecimalFormatSymbols(Locale.US));
        String str = f.format(d);
        if (str.length() > 8) {
            String[] strs = str.split("E");
            str = strs[0].substring(0, 8 - strs[1].length() - 1) + "E" + strs[1];
        }
        while (str.length() < 8) {
            str += " ";
        }
        return str;
    }
}
Example 20
Project: camel-master  File: NumberPatternFormat.java View source code
/**
     * Gets the number format if in use.
     *
     * @return the number format, or <tt>null</tt> if not in use
     */
protected NumberFormat getNumberFormat() {
    if (locale == null) {
        return null;
    }
    NumberFormat format = NumberFormat.getNumberInstance(locale);
    if (format instanceof DecimalFormat) {
        DecimalFormat df = (DecimalFormat) format;
        if (decimalSeparator != null && groupingSeparator != null) {
            if (!decimalSeparator.isEmpty() && !groupingSeparator.isEmpty()) {
                DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
                dfs.setDecimalSeparator(decimalSeparator.charAt(0));
                dfs.setGroupingSeparator(groupingSeparator.charAt(0));
                df.setDecimalFormatSymbols(dfs);
            }
        }
        if (!pattern.isEmpty()) {
            df.applyPattern(pattern);
        }
    }
    return format;
}
Example 21
Project: com.idega.core-master  File: CreditCardConverter.java View source code
public Object getAsObject(FacesContext context, UIComponent component, String newValue) throws ConverterException {
    Long convertedValue = null;
    if (newValue == null) {
        return newValue;
    }
    if (getPattern() == null) {
        setPattern("0000,0000,0000,0000");
    }
    if (getSeperator() == null) {
        setSeperator("-");
    }
    if (getDigits() < 0) {
        setDigits(16);
    }
    try {
        convertedValue = new Long(newValue.trim());
        DecimalFormat format = new DecimalFormat(getPattern());
        format.setMaximumFractionDigits(0);
        format.setMinimumIntegerDigits(getDigits());
        format.setMaximumIntegerDigits(getDigits());
        DecimalFormatSymbols dfs = format.getDecimalFormatSymbols();
        dfs.setGroupingSeparator(getSeperator().charAt(0));
        format.setDecimalFormatSymbols(dfs);
        return format.format(convertedValue);
    } catch (NumberFormatException nfe) {
        throw new ConverterException(nfe);
    }
}
Example 22
Project: deltaspike-master  File: NumberConfigPropertyProducer.java View source code
@Produces
@Dependent
@NumberConfig(name = "unused")
public Float produceNumberProperty(InjectionPoint injectionPoint) throws ParseException {
    // resolve the annotation
    NumberConfig metaData = getAnnotation(injectionPoint, NumberConfig.class);
    // get the configured value from the underlying configuration system
    String configuredValue = getPropertyValue(metaData.name(), metaData.defaultValue());
    if (configuredValue == null) {
        return null;
    }
    // format according to the given pattern
    DecimalFormat df = new DecimalFormat(metaData.pattern(), new DecimalFormatSymbols(Locale.US));
    return df.parse(configuredValue).floatValue();
}
Example 23
Project: geoserver-master  File: DecimalConverter.java View source code
@Override
public Double convertToObject(String value, Locale locale) {
    if (value == null || value.trim().length() == 0) {
        return null;
    }
    final NumberFormat format = getNumberFormat(locale);
    final DecimalFormatSymbols symbols = ((DecimalFormat) format).getDecimalFormatSymbols();
    if (value.equals(symbols.getNaN())) {
        return new Double(Double.NaN);
    } else if (value.equals(symbols.getInfinity())) {
        return new Double(Double.POSITIVE_INFINITY);
    } else if (value.equals("-" + symbols.getInfinity())) {
        return new Double(Double.NEGATIVE_INFINITY);
    } else {
        return super.convertToObject(value, locale);
    }
}
Example 24
Project: geotools-2.7.x-master  File: FilterFunction_numberFormat2.java View source code
public Object evaluate(Object feature) {
    String format;
    Double number;
    try {
        // attempt to get value and perform conversion
        format = getExpression(0).evaluate(feature, String.class);
    } catch (// probably a type error
    Exception // probably a type error
    e) {
        throw new IllegalArgumentException("Filter Function problem for function dateFormat argument #0 - expected type String");
    }
    try {
        // attempt to get value and perform conversion
        number = getExpression(1).evaluate(feature, Double.class);
    } catch (// probably a type error
    Exception // probably a type error
    e) {
        throw new IllegalArgumentException("Filter Function problem for function dateFormat argument #1 - expected type java.util.Date");
    }
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    if (params.size() > 2) {
        Character neg = getExpression(2).evaluate(feature, Character.class);
        symbols.setMinusSign(neg);
    }
    if (params.size() > 3) {
        Character dec = getExpression(3).evaluate(feature, Character.class);
        symbols.setDecimalSeparator(dec);
    }
    if (params.size() > 4) {
        Character grp = getExpression(4).evaluate(feature, Character.class);
        symbols.setGroupingSeparator(grp);
    }
    DecimalFormat numberFormat = new DecimalFormat(format, symbols);
    return numberFormat.format(number);
}
Example 25
Project: geotools-old-master  File: FilterFunction_numberFormat2.java View source code
public Object evaluate(Object feature) {
    String format;
    Double number;
    try {
        // attempt to get value and perform conversion
        format = getExpression(0).evaluate(feature, String.class);
    } catch (// probably a type error
    Exception // probably a type error
    e) {
        throw new IllegalArgumentException("Filter Function problem for function dateFormat argument #0 - expected type String");
    }
    try {
        // attempt to get value and perform conversion
        number = getExpression(1).evaluate(feature, Double.class);
    } catch (// probably a type error
    Exception // probably a type error
    e) {
        throw new IllegalArgumentException("Filter Function problem for function dateFormat argument #1 - expected type java.util.Date");
    }
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    if (params.size() > 2) {
        Character neg = getExpression(2).evaluate(feature, Character.class);
        symbols.setMinusSign(neg);
    }
    if (params.size() > 3) {
        Character dec = getExpression(3).evaluate(feature, Character.class);
        symbols.setDecimalSeparator(dec);
    }
    if (params.size() > 4) {
        Character grp = getExpression(4).evaluate(feature, Character.class);
        symbols.setGroupingSeparator(grp);
    }
    DecimalFormat numberFormat = new DecimalFormat(format, symbols);
    return numberFormat.format(number);
}
Example 26
Project: geotools_trunk-master  File: FilterFunction_numberFormat2.java View source code
public Object evaluate(Object feature) {
    String format;
    Double number;
    try {
        // attempt to get value and perform conversion
        format = getExpression(0).evaluate(feature, String.class);
    } catch (// probably a type error
    Exception // probably a type error
    e) {
        throw new IllegalArgumentException("Filter Function problem for function dateFormat argument #0 - expected type String");
    }
    try {
        // attempt to get value and perform conversion
        number = getExpression(1).evaluate(feature, Double.class);
    } catch (// probably a type error
    Exception // probably a type error
    e) {
        throw new IllegalArgumentException("Filter Function problem for function dateFormat argument #1 - expected type java.util.Date");
    }
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    if (params.size() > 2) {
        Character neg = getExpression(2).evaluate(feature, Character.class);
        symbols.setMinusSign(neg);
    }
    if (params.size() > 3) {
        Character dec = getExpression(3).evaluate(feature, Character.class);
        symbols.setDecimalSeparator(dec);
    }
    if (params.size() > 4) {
        Character grp = getExpression(4).evaluate(feature, Character.class);
        symbols.setGroupingSeparator(grp);
    }
    DecimalFormat numberFormat = new DecimalFormat(format, symbols);
    return numberFormat.format(number);
}
Example 27
Project: Goko-master  File: BigDecimalUtils.java View source code
public static String toString(BigDecimal value, Integer decimalCount) {
    DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance();
    DecimalFormatSymbols sym = df.getDecimalFormatSymbols();
    sym.setDecimalSeparator('.');
    if (decimalCount != null) {
        df.setMinimumFractionDigits(decimalCount);
        df.setMaximumFractionDigits(decimalCount);
    }
    df.setDecimalFormatSymbols(sym);
    df.setGroupingUsed(false);
    df.setParseBigDecimal(true);
    return df.format(value);
}
Example 28
Project: graphalytics-master  File: TemplateUtility.java View source code
/**
	 * Generates a string containing the name and size of a graph, with format: "graphname (X vertices, Y edges)".
	 *
	 * @param graph the graph to generate a human-readable string for
	 * @return a string representation of the graph name and size
	 */
public String formatGraphNameSize(GraphSet graph) {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setGroupingSeparator(' ');
    DecimalFormat df = new DecimalFormat("#,###", symbols);
    StringBuffer sb = new StringBuffer();
    sb.append(graph.getName()).append(" (").append(df.format(graph.getNumberOfVertices())).append(" vertices, ").append(df.format(graph.getNumberOfEdges())).append(" edges)");
    return sb.toString();
}
Example 29
Project: integrity-master  File: DecimalFormatOperation.java View source code
@Override
public String execute(BigDecimal aNumber, String[] someFormatString) {
    String tempFormatString = someFormatString.length > 0 ? someFormatString[0] : null;
    String tempLocaleCode = someFormatString.length > 1 ? someFormatString[1] : null;
    if (aNumber == null || tempFormatString == null) {
        return null;
    }
    DecimalFormat tempFormat;
    if (tempLocaleCode == null) {
        tempFormat = new DecimalFormat(tempFormatString);
    } else {
        Locale tempLocale = null;
        if (tempLocaleCode.length() == 2) {
            tempLocale = new Locale(tempLocaleCode);
        } else if (tempLocaleCode.length() == 4) {
            tempLocale = new Locale(tempLocaleCode.substring(0, 2), tempLocaleCode.substring(2, 4));
        }
        if (tempLocale == null) {
            throw new IllegalArgumentException("Was unable to parse given locale identifier '" + tempLocaleCode + "' into a valid locale!");
        }
        tempFormat = new DecimalFormat(tempFormatString, new DecimalFormatSymbols(tempLocale));
    }
    return tempFormat.format(aNumber);
}
Example 30
Project: invesdwin-util-master  File: ByteSizeTest.java View source code
@Test
public void test() {
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.BYTES).getValue(ByteSizeScale.BYTES)).isEqualTo(Decimal.ONE);
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.BYTES).getValue(ByteSizeScale.KILOBYTES)).isEqualTo(new Decimal("0.001"));
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.BYTES).getValue(ByteSizeScale.MEGABYTES).toString()).isEqualTo(new Decimal("0.000001").toString());
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.BYTES).getValue(ByteSizeScale.MEGABYTES)).isEqualTo(new Decimal("0.000001"));
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.KILOBYTES).getValue(ByteSizeScale.KILOBYTES)).isEqualTo(Decimal.ONE);
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.KILOBYTES).getValue(ByteSizeScale.MEGABYTES)).isEqualTo(new Decimal("0.001"));
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.KILOBYTES).getValue(ByteSizeScale.BYTES)).isEqualTo(new Decimal("1000"));
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.MEGABYTES).getValue(ByteSizeScale.MEGABYTES)).isEqualTo(Decimal.ONE);
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.MEGABYTES).getValue(ByteSizeScale.KILOBYTES)).isEqualTo(new Decimal("1000"));
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.MEGABYTES).getValue(ByteSizeScale.BYTES)).isEqualTo(new Decimal("1000000"));
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.BYTES).toString(ByteSizeScale.BYTES, true)).isEqualTo("1B");
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.BYTES).toString(ByteSizeScale.KILOBYTES, true)).isEqualTo("0" + DecimalFormatSymbols.getInstance(Locale.ENGLISH).getDecimalSeparator() + "001KB");
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.BYTES).toString(ByteSizeScale.MEGABYTES, true)).isEqualTo("0" + DecimalFormatSymbols.getInstance(Locale.ENGLISH).getDecimalSeparator() + "000001MB");
    Assertions.assertThat(new ByteSize(Decimal.ONE, ByteSizeScale.BYTES).toString(ByteSizeScale.TERABYTES, true)).isEqualTo("0TB");
}
Example 31
Project: JavascriptGame-master  File: GeometryTest.java View source code
@Test
public void testCoordinatesAfterRotation() {
    Vector2 point = new Vector2(2d, 0d);
    // rotation of 50 degrees
    Double rotation = 50 * Math.PI / 180;
    DecimalFormat df = new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.ENGLISH));
    assertThat(df.format(Geometry.coordinatesAfterRotation(point, rotation).x)).isEqualTo("1.29");
    assertThat(df.format(Geometry.coordinatesAfterRotation(point, rotation).y)).isEqualTo("1.53");
}
Example 32
Project: JAVMovieScraper-master  File: Rating.java View source code
/**
	 * Uses the maxRating and rating score to convert the rating to a score out of 10 with one decimal place
	 * @return
	 */
public String getRatingOutOfTen() {
    if (rating == null || rating.equals("") || maxRating == 0.0)
        return "";
    try {
        double ratingValue = Double.valueOf(rating).doubleValue();
        double ratingOutOfTenValue = 10 * (ratingValue / ((double) maxRating));
        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        symbols.setDecimalSeparator('.');
        //format to 1 decimal place
        DecimalFormat oneDigit = new DecimalFormat("###0.0", symbols);
        return oneDigit.format(ratingOutOfTenValue);
    } catch (NumberFormatException e) {
        return "";
    }
}
Example 33
Project: jtwig-master  File: NumberFormatFunction.java View source code
private String numberFormat(Object numberArg, BigDecimal fractionDigits, String decimalSeparator, String groupingSeparator) {
    Object number = (numberArg == null) ? 0 : numberArg;
    DecimalFormat numberFormat = new DecimalFormat();
    DecimalFormatSymbols decimalFormatSymbols = numberFormat.getDecimalFormatSymbols();
    if (fractionDigits != null) {
        numberFormat.setMaximumFractionDigits(fractionDigits.intValue());
        numberFormat.setMinimumFractionDigits(fractionDigits.intValue());
    }
    if (decimalSeparator != null && !decimalSeparator.isEmpty())
        decimalFormatSymbols.setDecimalSeparator(decimalSeparator.charAt(0));
    else
        decimalFormatSymbols.setDecimalSeparator('.');
    if (groupingSeparator != null && !groupingSeparator.isEmpty())
        decimalFormatSymbols.setGroupingSeparator(groupingSeparator.charAt(0));
    else
        numberFormat.setGroupingUsed(false);
    numberFormat.setDecimalFormatSymbols(decimalFormatSymbols);
    return numberFormat.format(number);
}
Example 34
Project: many-ql-master  File: DecimalQuestion.java View source code
@Override
public DecimalValue getValue() {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setGroupingSeparator(',');
    symbols.setDecimalSeparator('.');
    String pattern = "#0.0#";
    DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
    decimalFormat.setParseBigDecimal(true);
    // parse the string
    BigDecimal bigDecimal;
    try {
        bigDecimal = (BigDecimal) decimalFormat.parse(textField.getText());
        return new DecimalValue(bigDecimal);
    } catch (ParseException e) {
        return new DecimalValue(new BigDecimal(0.0));
    }
}
Example 35
Project: mv2m-master  File: CurrencyConverterViewModel.java View source code
public void calculate() {
    String inputString = model.input.get();
    try {
        final float input = Float.parseFloat(inputString);
        subscribe(new Action1<Boolean>() {

            @Override
            public void call(Boolean b) {
                loading.set(b);
            }
        }, rateLoader.loadRate(), new Action1<Float>() {

            @Override
            public void call(Float rate) {
                DecimalFormat decimalFormat = new DecimalFormat("0.00", DecimalFormatSymbols.getInstance(Locale.US));
                model.output.set(decimalFormat.format(input * rate));
            }
        }, new Action1<Throwable>() {

            @Override
            public void call(Throwable throwable) {
                messageManager.showMessage(activityHolder, R.string.error_loading_rate);
            }
        });
    } catch (NumberFormatException e) {
        messageManager.showMessage(activityHolder, R.string.conversion_error);
    }
}
Example 36
Project: Nuclear-Control-master  File: StringUtils.java View source code
private static DecimalFormat getFormatter() {
    if (formatter == null) {
        DecimalFormat lFormatter = new DecimalFormat("#,###.###");
        DecimalFormatSymbols smb = new DecimalFormatSymbols();
        smb.setGroupingSeparator(' ');
        lFormatter.setDecimalFormatSymbols(smb);
        formatter = lFormatter;
    }
    return formatter;
}
Example 37
Project: openjdk-master  File: SerializationLoadTest.java View source code
public static void main(String[] args) {
    try {
        InputStream istream1 = HexDumpReader.getStreamFromHexDump("DecimalFormat.114.txt");
        ObjectInputStream p = new ObjectInputStream(istream1);
        CheckDecimalFormat it = (CheckDecimalFormat) p.readObject();
        System.out.println("1.1.4 DecimalFormat Loaded ok.");
        System.out.println(it.Update());
        System.out.println("Called Update successfully.");
        istream1.close();
        InputStream istream2 = HexDumpReader.getStreamFromHexDump("DecimalFormatSymbols.114.txt");
        ObjectInputStream p2 = new ObjectInputStream(istream2);
        CheckDecimalFormatSymbols it2 = (CheckDecimalFormatSymbols) p2.readObject();
        System.out.println("1.1.4 DecimalFormatSymbols Loaded ok.");
        System.out.println("getDigit : " + it2.Update());
        System.out.println("Called Update successfully.");
        istream2.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 38
Project: org.handwerkszeug.mvnhack-master  File: DecimalFormatUtil.java View source code
private static void init() {
    for (Locale locale : DecimalFormatSymbols.getAvailableLocales()) {
        final DecimalFormatSymbols localeSymbols = DecimalFormatSymbols.getInstance(locale);
        final String symbol = localeSymbols.getCurrencySymbol();
        Character c = Character.valueOf(symbol.toCharArray()[0]);
        SPECIAL_CURRENCY_SYMBOLS = ArrayUtil.add(SPECIAL_CURRENCY_SYMBOLS, c);
    }
}
Example 39
Project: owsi-core-parent-master  File: CoreRenderers.java View source code
private static Function<Locale, DecimalFormat> percentDecimalFormatFunction(final String pattern, final RoundingMode roundingMode) {
    return new SerializableFunction<Locale, DecimalFormat>() {

        private static final long serialVersionUID = 1L;

        @Override
        public DecimalFormat apply(@Nonnull Locale input) {
            DecimalFormat df = new DecimalFormat(pattern, new DecimalFormatSymbols(input));
            df.setRoundingMode(roundingMode);
            df.setMultiplier(100);
            return df;
        }
    };
}
Example 40
Project: pageobject-master  File: DefaultFormattingService.java View source code
/**
	 * @see cz.cmhb.olin.selenium.FormattingService#formatNumber(Number)
	 */
public String formatNumber(Number number) {
    if (number == null) {
        return null;
    }
    DecimalFormat numberFormat = new DecimalFormat(getNumberFormat());
    DecimalFormatSymbols decimalFormatSymbols = numberFormat.getDecimalFormatSymbols();
    decimalFormatSymbols.setDecimalSeparator(getDecimalSeparator());
    numberFormat.setDecimalFormatSymbols(decimalFormatSymbols);
    return numberFormat.format(number);
}
Example 41
Project: Pebble-master  File: NumberFormatFilter.java View source code
@Override
public Object apply(Object input, Map<String, Object> args) {
    if (input == null) {
        return null;
    }
    Number number = (Number) input;
    EvaluationContext context = (EvaluationContext) args.get("_context");
    Locale locale = context.getLocale();
    if (args.get("format") != null) {
        Format format = new DecimalFormat((String) args.get("format"), new DecimalFormatSymbols(locale));
        return format.format(number);
    } else {
        NumberFormat numberFormat = NumberFormat.getInstance(locale);
        return numberFormat.format(number);
    }
}
Example 42
Project: pentaho-reporting-master  File: TextFunctionTest.java View source code
public Object[][] createDataTest() {
    final Locale locale = getContext().getLocalizationContext().getLocale();
    final DecimalFormat format = new DecimalFormat("#0.#######", new DecimalFormatSymbols(locale));
    return new Object[][] { { "TEXT(\"HI\")", "HI" }, { "TEXT(5)", "5" }, { "TEXT(100.01)", format.format(100.01) } };
}
Example 43
Project: poly-ql-master  File: IntInput.java View source code
@Override
public Value<?> getValue() {
    if (!widget.getText().isEmpty()) {
        String groupingSymbol = "\\" + String.valueOf(new DecimalFormatSymbols().getGroupingSeparator());
        String stringValue = widget.getText();
        return new Int(Integer.parseInt(stringValue.replaceAll(groupingSymbol, "")));
    }
    return new Undefined();
}
Example 44
Project: rdt-master  File: NonBlockingSocketReader.java View source code
public void testOperationsPerSecond(double sleepTime, double blockingTime) throws Exception {
    DecimalFormat format = new DecimalFormat();
    format.setMaximumFractionDigits(10);
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    out.println("sleepTime " + format.format(sleepTime));
    out.println("blockingTime " + format.format(blockingTime));
    out.println("startCalculation");
    Thread.sleep(2000);
    out.println("stopCalculation");
    Thread.sleep(500);
    int operationsPerSecond = Integer.parseInt(reader.readLine());
    System.out.println("sleeptime/blockingTime/OperationsPerSecond: " + format.format(sleepTime) + "/" + format.format(blockingTime) + "/" + operationsPerSecond);
}
Example 45
Project: SitJar-master  File: FormatTool.java View source code
public static String getFormD(double d, int numOfDecimalPlace, char decimalSeparator) {
    DecimalFormatSymbols usedFormatSymbols = new DecimalFormatSymbols();
    usedFormatSymbols.setDecimalSeparator(decimalSeparator);
    StringBuilder pattern = new StringBuilder("#.");
    for (int i = 0; i < numOfDecimalPlace; i++) {
        pattern.append("#");
    }
    return (new DecimalFormat(pattern.toString(), usedFormatSymbols).format(d));
}
Example 46
Project: Skylark-master  File: Video.java View source code
public String format(boolean includeShortUrl) {
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
    symbols.setGroupingSeparator(',');
    DecimalFormat formatter = new DecimalFormat("###,###", symbols);
    StringBuilder sb = new StringBuilder();
    sb.append(String.format(" | &b%s&r", title));
    sb.append(String.format(" | by &b%s&r", channelTitle));
    if (durationInSeconds != 0)
        sb.append(String.format(" | %s long", TimeDuration.formatSeconds(durationInSeconds)));
    if (views != 0)
        sb.append(String.format(" | %s view%s", formatter.format(views), views == 1 ? "" : "s"));
    if (likes + dislikes != 0) {
        DecimalFormatSymbols symbols2 = DecimalFormatSymbols.getInstance();
        symbols2.setDecimalSeparator('.');
        DecimalFormat formatter2 = new DecimalFormat("###.##", symbols2);
        sb.append(String.format(" | +%s / -%s (%s%%)", formatter.format(likes), formatter.format(dislikes), formatter2.format(100d * likes / (likes + dislikes))));
    }
    if (includeShortUrl)
        sb.append(String.format(" | %s", getShortURL()));
    String ret = sb.toString().substring(3);
    ret = ret.replace("&b", Colors.BOLD);
    ret = ret.replace("&r", Colors.NORMAL);
    return ret;
}
Example 47
Project: SmartETL-master  File: TextFunctionTest.java View source code
public Object[][] createDataTest() {
    final Locale locale = getContext().getLocalizationContext().getLocale();
    final DecimalFormat format = new DecimalFormat("#0.#######", new DecimalFormatSymbols(locale));
    return new Object[][] { { "TEXT(\"HI\")", "HI" }, { "TEXT(5)", "5" }, { "TEXT(100.01)", format.format(100.01) } };
}
Example 48
Project: StaticPages-master  File: DecimalFormatManager.java View source code
public static void setDefaults(DecimalFormatSymbols decimalformatsymbols) {
    /*  35*/
    decimalformatsymbols.setDecimalSeparator('.');
    /*  36*/
    decimalformatsymbols.setGroupingSeparator(',');
    /*  37*/
    decimalformatsymbols.setInfinity("Infinity");
    /*  38*/
    decimalformatsymbols.setMinusSign('-');
    /*  39*/
    decimalformatsymbols.setNaN("NaN");
    /*  40*/
    decimalformatsymbols.setPercent('%');
    /*  41*/
    decimalformatsymbols.setPerMill('‰');
    /*  42*/
    decimalformatsymbols.setZeroDigit('0');
    /*  43*/
    decimalformatsymbols.setDigit('#');
    /*  44*/
    decimalformatsymbols.setPatternSeparator(';');
}
Example 49
Project: Strata-master  File: DoubleValueFormatter.java View source code
//-------------------------------------------------------------------------
private DecimalFormat getDecimalPlacesFormat(int decimalPlaces) {
    if (!displayFormatCache.containsKey(decimalPlaces)) {
        DecimalFormat format = new DecimalFormat("#,##0;(#,##0)", new DecimalFormatSymbols(Locale.ENGLISH));
        format.setMinimumFractionDigits(decimalPlaces);
        format.setMaximumFractionDigits(decimalPlaces);
        displayFormatCache.put(decimalPlaces, format);
        return format;
    }
    return displayFormatCache.get(decimalPlaces);
}
Example 50
Project: voxels-master  File: VoxGameExporter.java View source code
// write the file
@Override
protected boolean writeFile() throws IOException {
    // write dimension information
    int[] size = getSize();
    fileOut.writeBytes((size[0] + 1) + " " + (size[1] + 1) + " " + (size[2] + 1) + "\r\n\r\n");
    // get and prepare variables
    int[] min = getMin();
    int[] max = getMax();
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setGroupingSeparator(',');
    DecimalFormat df = new DecimalFormat("#.###", otherSymbols);
    df.setRoundingMode(RoundingMode.HALF_UP);
    df.setGroupingUsed(false);
    setActivity("Exporting to file...", false);
    // write data (set flag, r, g, b)
    for (int y = max[1]; y > min[1] - 1; y--) {
        setProgress((1 - ((y - min[1]) / (float) size[1])) * 100);
        for (int x = max[0]; x > min[0] - 1; x--) {
            for (int z = min[2]; z <= max[2]; z++) {
                Voxel voxel = data.searchVoxel(new int[] { x, y, z }, false);
                if (voxel == null) {
                    fileOut.writeBytes("0 1 1 1 ");
                } else {
                    Color color = voxel.getColor();
                    fileOut.writeBytes("1 " + df.format(color.getRed() / 255f) + " " + df.format(color.getGreen() / 255f) + " " + df.format(color.getBlue() / 255f) + " ");
                }
            }
        }
    }
    // success
    return true;
}
Example 51
Project: whitebox-geospatial-analysis-tools-master  File: StringUtilities.java View source code
public static boolean isStringNumeric(String str) {
    try {
        if (str.isEmpty()) {
            return false;
        }
        DecimalFormatSymbols currentLocaleSymbols = DecimalFormatSymbols.getInstance();
        char localeMinusSign = currentLocaleSymbols.getMinusSign();
        if (!Character.isDigit(str.charAt(0)) && str.charAt(0) != localeMinusSign) {
            return false;
        }
        boolean isDecimalSeparatorFound = false;
        char localeDecimalSeparator = currentLocaleSymbols.getDecimalSeparator();
        for (char c : str.substring(1).toCharArray()) {
            if (!Character.isDigit(c)) {
                if (c == localeDecimalSeparator && !isDecimalSeparatorFound) {
                    isDecimalSeparatorFound = true;
                    continue;
                }
                return false;
            }
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}
Example 52
Project: bugvm-master  File: FuncFormatNumb.java View source code
/**
   * Execute the function.  The function must return
   * a valid object.
   * @param xctxt The current execution context.
   * @return A valid XObject.
   *
   * @throws javax.xml.transform.TransformerException
   */
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException {
    // A bit of an ugly hack to get our context.
    ElemTemplateElement templElem = (ElemTemplateElement) xctxt.getNamespaceContext();
    StylesheetRoot ss = templElem.getStylesheetRoot();
    java.text.DecimalFormat formatter = null;
    java.text.DecimalFormatSymbols dfs = null;
    double num = getArg0().execute(xctxt).num();
    String patternStr = getArg1().execute(xctxt).str();
    // TODO: what should be the behavior here??
    if (patternStr.indexOf(0x00A4) > 0)
        // currency sign not allowed
        ss.error(XSLTErrorResources.ER_CURRENCY_SIGN_ILLEGAL);
    // decimal-format declared in the stylesheet!(xsl:decimal-format
    try {
        Expression arg2Expr = getArg2();
        if (null != arg2Expr) {
            String dfName = arg2Expr.execute(xctxt).str();
            QName qname = new QName(dfName, xctxt.getNamespaceContext());
            dfs = ss.getDecimalFormatComposed(qname);
            if (null == dfs) {
                warn(xctxt, XSLTErrorResources.WG_NO_DECIMALFORMAT_DECLARATION, //"not found!!!
                new Object[] { dfName });
            //formatter = new java.text.DecimalFormat(patternStr);
            } else {
                //formatter = new java.text.DecimalFormat(patternStr, dfs);
                formatter = new java.text.DecimalFormat();
                formatter.setDecimalFormatSymbols(dfs);
                formatter.applyLocalizedPattern(patternStr);
            }
        }
        //else
        if (null == formatter) {
            // look for a possible default decimal-format
            dfs = ss.getDecimalFormatComposed(new QName(""));
            if (dfs != null) {
                formatter = new java.text.DecimalFormat();
                formatter.setDecimalFormatSymbols(dfs);
                formatter.applyLocalizedPattern(patternStr);
            } else {
                dfs = new java.text.DecimalFormatSymbols(java.util.Locale.US);
                dfs.setInfinity(Constants.ATTRVAL_INFINITY);
                dfs.setNaN(Constants.ATTRVAL_NAN);
                formatter = new java.text.DecimalFormat();
                formatter.setDecimalFormatSymbols(dfs);
                if (null != patternStr)
                    formatter.applyLocalizedPattern(patternStr);
            }
        }
        return new XString(formatter.format(num));
    } catch (Exception iae) {
        templElem.error(XSLTErrorResources.ER_MALFORMED_FORMAT_STRING, new Object[] { patternStr });
        return XString.EMPTYSTRING;
    }
}
Example 53
Project: JFugue-for-Android-master  File: FuncFormatNumb.java View source code
/**
   * Execute the function.  The function must return
   * a valid object.
   * @param xctxt The current execution context.
   * @return A valid XObject.
   *
   * @throws javax.xml.transform.TransformerException
   */
public XObject execute(XPathContext xctxt) throws TransformerException {
    // A bit of an ugly hack to get our context.
    ElemTemplateElement templElem = (ElemTemplateElement) xctxt.getNamespaceContext();
    StylesheetRoot ss = templElem.getStylesheetRoot();
    java.text.DecimalFormat formatter = null;
    java.text.DecimalFormatSymbols dfs = null;
    double num = getArg0().execute(xctxt).num();
    String patternStr = getArg1().execute(xctxt).str();
    // TODO: what should be the behavior here??
    if (patternStr.indexOf(0x00A4) > 0)
        // currency sign not allowed
        ss.error(XSLTErrorResources.ER_CURRENCY_SIGN_ILLEGAL);
    // decimal-format declared in the stylesheet!(xsl:decimal-format
    try {
        Expression arg2Expr = getArg2();
        if (null != arg2Expr) {
            String dfName = arg2Expr.execute(xctxt).str();
            QName qname = new QName(dfName, xctxt.getNamespaceContext());
            dfs = ss.getDecimalFormatComposed(qname);
            if (null == dfs) {
                warn(xctxt, XSLTErrorResources.WG_NO_DECIMALFORMAT_DECLARATION, //"not found!!!
                new Object[] { dfName });
            //formatter = new java.text.DecimalFormat(patternStr);
            } else {
                //formatter = new java.text.DecimalFormat(patternStr, dfs);
                formatter = new java.text.DecimalFormat();
                formatter.setDecimalFormatSymbols(dfs);
                formatter.applyLocalizedPattern(patternStr);
            }
        }
        //else
        if (null == formatter) {
            // look for a possible default decimal-format
            dfs = ss.getDecimalFormatComposed(new QName(""));
            if (dfs != null) {
                formatter = new java.text.DecimalFormat();
                formatter.setDecimalFormatSymbols(dfs);
                formatter.applyLocalizedPattern(patternStr);
            } else {
                dfs = new java.text.DecimalFormatSymbols(java.util.Locale.US);
                dfs.setInfinity(Constants.ATTRVAL_INFINITY);
                dfs.setNaN(Constants.ATTRVAL_NAN);
                formatter = new java.text.DecimalFormat();
                formatter.setDecimalFormatSymbols(dfs);
                if (null != patternStr)
                    formatter.applyLocalizedPattern(patternStr);
            }
        }
        return new XString(formatter.format(num));
    } catch (Exception iae) {
        templElem.error(XSLTErrorResources.ER_MALFORMED_FORMAT_STRING, new Object[] { patternStr });
        return XString.EMPTYSTRING;
    }
}
Example 54
Project: activemq-master  File: TimeUtils.java View source code
/**
     * Prints the duration in a human readable format as X days Y hours Z minutes etc.
     *
     * @param uptime the up-time in milliseconds
     *
     * @return the time used for displaying on screen or in logs
     */
public static String printDuration(double uptime) {
    // Code taken from Karaf
    // https://svn.apache.org/repos/asf/karaf/trunk/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/InfoAction.java
    NumberFormat fmtI = new DecimalFormat("###,###", new DecimalFormatSymbols(Locale.ENGLISH));
    NumberFormat fmtD = new DecimalFormat("###,##0.000", new DecimalFormatSymbols(Locale.ENGLISH));
    uptime /= 1000;
    if (uptime < 60) {
        return fmtD.format(uptime) + " seconds";
    }
    uptime /= 60;
    if (uptime < 60) {
        long minutes = (long) uptime;
        String s = fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
        return s;
    }
    uptime /= 60;
    if (uptime < 24) {
        long hours = (long) uptime;
        long minutes = (long) ((uptime - hours) * 60);
        String s = fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
        if (minutes != 0) {
            s += " " + fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
        }
        return s;
    }
    uptime /= 24;
    long days = (long) uptime;
    long hours = (long) ((uptime - days) * 24);
    String s = fmtI.format(days) + (days > 1 ? " days" : " day");
    if (hours != 0) {
        s += " " + fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
    }
    return s;
}
Example 55
Project: codjo-broadcast-master  File: NumberColumnGenerator.java View source code
/**
     * Initialisation du separateur de decimales pour le format de sortie.
     *
     * @param decimalSeparator Le separateur de decimales a utiliser
     * @param decimalPattern   Description of the Parameter
     */
private void initFormat(String decimalSeparator, String decimalPattern) {
    if (".".equals(decimalSeparator)) {
        formatFloatOUT = new DecimalFormat(decimalPattern, new DecimalFormatSymbols(Locale.ENGLISH));
    } else if (",".equals(decimalSeparator)) {
        formatFloatOUT = new java.text.DecimalFormat(decimalPattern, new DecimalFormatSymbols(Locale.FRENCH));
    } else {
        throw new IllegalArgumentException("Separateur de décimal non supporté : " + decimalSeparator);
    }
}
Example 56
Project: codjo-standalone-common-master  File: NumberFormatRenderer.java View source code
private void initNumberFormat() {
    NUMBER_FORMAT_2DEC = new DecimalFormat("#####0.00", new DecimalFormatSymbols(locale));
    NUMBER_FORMAT_5DEC = new DecimalFormat("#####0.00000", new DecimalFormatSymbols(locale));
    NUMBER_FORMAT_6DEC = new DecimalFormat("#####0.000000", new DecimalFormatSymbols(Locale.FRANCE));
    NUMBER_FORMAT_8DEC = new DecimalFormat("#####0.00000000", new DecimalFormatSymbols(Locale.FRANCE));
    NUMBER_FORMAT_15DEC = new DecimalFormat("#####0.000000000000000", new DecimalFormatSymbols(Locale.FRANCE));
    NUMBER_FORMAT_DEFAULT = NumberFormat.getNumberInstance(Locale.FRANCE);
}
Example 57
Project: confeito-master  File: DecimalFormatUtil.java View source code
public static String normalize(String s, Locale locale) {
    if (StringUtil.isEmpty(s)) {
        return null;
    }
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
    char groupingSeparator = symbols.getGroupingSeparator();
    char decimalSeparator = symbols.getDecimalSeparator();
    final StringBuilder builder = new StringBuilder(20);
    for (int i = 0; i < s.length(); ++i) {
        char c = s.charAt(i);
        if (c == groupingSeparator) {
            continue;
        } else if (c == decimalSeparator) {
            c = '.';
        } else if (ArrayUtil.contains(SPECIAL_CURRENCY_SYMBOLS, Character.valueOf(c))) {
            continue;
        }
        builder.append(c);
    }
    return builder.toString();
}
Example 58
Project: financisto-master  File: CurrencyCache.java View source code
public static DecimalFormat createCurrencyFormat(Currency c) {
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setDecimalSeparator(charOrEmpty(c.decimalSeparator, dfs.getDecimalSeparator()));
    dfs.setGroupingSeparator(charOrEmpty(c.groupSeparator, dfs.getGroupingSeparator()));
    dfs.setMonetaryDecimalSeparator(dfs.getDecimalSeparator());
    dfs.setCurrencySymbol(c.symbol);
    DecimalFormat df = new DecimalFormat("#,##0.00", dfs);
    df.setGroupingUsed(dfs.getGroupingSeparator() > 0);
    df.setMinimumFractionDigits(c.decimals);
    df.setMaximumFractionDigits(c.decimals);
    df.setDecimalSeparatorAlwaysShown(false);
    return df;
}
Example 59
Project: framework-master  File: TextFieldWithPropertyFormatter.java View source code
@Override
protected void setup() {
    /*
         * Formatter that: - formats in UK currency style - scales to 2 fraction
         * digits - rounds half up
         */
    // Property containing BigDecimal
    property = new Property<BigDecimal>() {

        private BigDecimal value;

        @Override
        public BigDecimal getValue() {
            return value;
        }

        @Override
        public void setValue(BigDecimal newValue) throws ReadOnlyException {
            value = newValue;
        }

        @Override
        public Class<BigDecimal> getType() {
            return BigDecimal.class;
        }

        @Override
        public boolean isReadOnly() {
            return false;
        }

        @Override
        public void setReadOnly(boolean newStatus) {
        // ignore
        }
    };
    formatter = new PropertyFormatter<BigDecimal>(property) {

        private final DecimalFormat df = new DecimalFormat("#,##0.00", new DecimalFormatSymbols(new Locale("en", "UK")));

        {
            df.setParseBigDecimal(true);
        // df.setRoundingMode(RoundingMode.HALF_UP);
        }

        @Override
        public String format(BigDecimal value) {
            final String retVal;
            if (value == null) {
                retVal = "";
            } else {
                retVal = df.format(value);
            }
            return retVal;
        }

        @Override
        public BigDecimal parse(String formattedValue) throws Exception {
            if (formattedValue != null && formattedValue.trim().length() != 0) {
                BigDecimal value = (BigDecimal) df.parse(formattedValue);
                value = value.setScale(2, BigDecimal.ROUND_HALF_UP);
                return value;
            }
            return null;
        }
    };
    final TextField tf1 = new TextField();
    tf1.setPropertyDataSource(formatter);
    addComponent(tf1);
    Button b = new Button("Sync (typing 12345.6789 and clicking this should format field)");
    b.addClickListener(new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
        }
    });
    addComponent(b);
    b = new Button("Set '12345.6789' to textfield on the server side");
    b.addClickListener(new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            tf1.setValue("12345.6789");
        }
    });
    addComponent(b);
}
Example 60
Project: gdl-tools-master  File: OpenEHRNumberFormat.java View source code
public static DecimalFormat getDecimalFormat(Integer precision) {
    DecimalFormatSymbols custom = new DecimalFormatSymbols();
    custom.setDecimalSeparator(DV_QUANTITY_DECIMAL_SEPARATOR);
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(custom);
    format.setGroupingUsed(false);
    if (precision != null) {
        format.setMinimumFractionDigits(precision);
        format.setMaximumFractionDigits(precision);
    }
    return format;
}
Example 61
Project: hawtjms-master  File: TimeUtils.java View source code
/**
     * Prints the duration in a human readable format as X days Y hours Z minutes etc.
     *
     * @param uptime
     *        the uptime in millis
     * @return the time used for displaying on screen or in logs
     */
public static String printDuration(double uptime) {
    NumberFormat fmtI = new DecimalFormat("###,###", new DecimalFormatSymbols(Locale.ENGLISH));
    NumberFormat fmtD = new DecimalFormat("###,##0.000", new DecimalFormatSymbols(Locale.ENGLISH));
    uptime /= 1000;
    if (uptime < 60) {
        return fmtD.format(uptime) + " seconds";
    }
    uptime /= 60;
    if (uptime < 60) {
        long minutes = (long) uptime;
        String s = fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
        return s;
    }
    uptime /= 60;
    if (uptime < 24) {
        long hours = (long) uptime;
        long minutes = (long) ((uptime - hours) * 60);
        String s = fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
        if (minutes != 0) {
            s += " " + fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
        }
        return s;
    }
    uptime /= 24;
    long days = (long) uptime;
    long hours = (long) ((uptime - days) * 24);
    String s = fmtI.format(days) + (days > 1 ? " days" : " day");
    if (hours != 0) {
        s += " " + fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
    }
    return s;
}
Example 62
Project: head-master  File: AccountingDataCacheManagerTest.java View source code
@Test
public void testAccoutingDataFromCache() throws Exception {
    List<AccountingDto> data = new ArrayList<AccountingDto>();
    data.add(new AccountingDto("branch", "2010-10-12", "RECEIPT", "234324", "GLCODE NAME", "5", "546"));
    data.add(new AccountingDto("branch", "2010-10-12", "RECEIPT", "234324", "GLCODE NAME", "5", "546"));
    LocalDate date = new LocalDate(2010, 10, 12);
    String cacheFileName = cacheManager.getCacheFileName(date, date);
    cacheManager.writeAccountingDataToCache(data, cacheFileName);
    List<AccountingDto> accountingData = cacheManager.getExportDetails(cacheFileName);
    Assert.assertEquals(2, accountingData.size());
    DecimalFormat df = new DecimalFormat("#.0", new DecimalFormatSymbols(Locale.ENGLISH));
    for (AccountingDto dto : accountingData) {
        Assert.assertEquals("branch;2010-10-12;RECEIPT;234324;GLCODE NAME;" + df.format(5.0) + ";" + df.format(546.0), dto.toString());
        Assert.assertEquals("GLCODE NAME", dto.getGlCodeName());
    }
}
Example 63
Project: jMathLib-master  File: format.java View source code
/**Returns an enviroment variable
	@param operand[0] = the name of the variable
	@param operand[1] = a default value (optional)
	@return the enviroment value*/
public OperandToken evaluate(Token[] operands, GlobalValues globals) {
    OperandToken result = null;
    if (getNArgIn(operands) > 1)
        throwMathLibException("format: number of arguments > 1");
    if ((getNArgIn(operands) == 1) && (!(operands[0] instanceof CharToken)))
        throwMathLibException("format: argument must be a string");
    String type = "";
    if (getNArgIn(operands) == 1)
        type = operands[0].toString();
    if (type.equals("short"))
        globals.setNumberFormat(new DecimalFormat("0.0000", new DecimalFormatSymbols(Locale.ENGLISH)));
    else if (type.equals("long"))
        globals.setNumberFormat(new DecimalFormat("0.000000000000000", new DecimalFormatSymbols(Locale.ENGLISH)));
    else if (type.equals("short e"))
        globals.setNumberFormat(new DecimalFormat("0.0000E000", new DecimalFormatSymbols(Locale.ENGLISH)));
    else if (type.equals("long e"))
        globals.setNumberFormat(new DecimalFormat("0.000000000000000E000", new DecimalFormatSymbols(Locale.ENGLISH)));
    else if (type.equals("short g"))
        globals.setNumberFormat(new DecimalFormat("0.0000E000", new DecimalFormatSymbols(Locale.ENGLISH)));
    else if (type.equals("long g"))
        globals.setNumberFormat(new DecimalFormat("0.000000000000000E000", new DecimalFormatSymbols(Locale.ENGLISH)));
    else if (type.equals("short eng"))
        globals.setNumberFormat(new DecimalFormat("0.0000E000", new DecimalFormatSymbols(Locale.ENGLISH)));
    else if (type.equals("long eng"))
        globals.setNumberFormat(new DecimalFormat("0.000000000000000E000", new DecimalFormatSymbols(Locale.ENGLISH)));
    else
        globals.setNumberFormat(new DecimalFormat("0.0000", new DecimalFormatSymbols(Locale.ENGLISH)));
    return result;
}
Example 64
Project: mapfish-print-master  File: GridLabelFormat.java View source code
@Override
public final String format(final double value, final String unit) {
    DecimalFormat decimalFormat = null;
    if (this.formatDecimalSeparator != null || this.formatGroupingSeparator != null) {
        // if custom separator characters are given, use them to create the format
        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        if (this.formatDecimalSeparator != null) {
            symbols.setDecimalSeparator(this.formatDecimalSeparator.charAt(0));
        }
        if (this.formatGroupingSeparator != null) {
            symbols.setGroupingSeparator(this.formatGroupingSeparator.charAt(0));
        }
        decimalFormat = new DecimalFormat(this.valueFormat, symbols);
    } else {
        decimalFormat = new DecimalFormat(this.valueFormat);
    }
    return decimalFormat.format(value) + String.format(this.unitFormat, unit);
}
Example 65
Project: mifos-head-master  File: AccountingDataCacheManagerTest.java View source code
@Test
public void testAccoutingDataFromCache() throws Exception {
    List<AccountingDto> data = new ArrayList<AccountingDto>();
    data.add(new AccountingDto("branch", "2010-10-12", "RECEIPT", "234324", "GLCODE NAME", "5", "546"));
    data.add(new AccountingDto("branch", "2010-10-12", "RECEIPT", "234324", "GLCODE NAME", "5", "546"));
    LocalDate date = new LocalDate(2010, 10, 12);
    String cacheFileName = cacheManager.getCacheFileName(date, date);
    cacheManager.writeAccountingDataToCache(data, cacheFileName);
    List<AccountingDto> accountingData = cacheManager.getExportDetails(cacheFileName);
    Assert.assertEquals(2, accountingData.size());
    DecimalFormat df = new DecimalFormat("#.0", new DecimalFormatSymbols(Locale.ENGLISH));
    for (AccountingDto dto : accountingData) {
        Assert.assertEquals("branch;2010-10-12;RECEIPT;234324;GLCODE NAME;" + df.format(5.0) + ";" + df.format(546.0), dto.toString());
        Assert.assertEquals("GLCODE NAME", dto.getGlCodeName());
    }
}
Example 66
Project: monticore-master  File: CartesianToPolar.java View source code
/**
   * Transforms carthesian to polar coordinates
   * 
   * @param a Coordinate to transform
   */
@Override
public void visit(mc.examples.cartesian.coordcartesian._ast.ASTCoordinate a) {
    DecimalFormat Reals = new DecimalFormat("0.000", new DecimalFormatSymbols(Locale.GERMAN));
    // d = sqrt(x*x + y*y)
    double d = Math.sqrt(a.getX() * a.getX() + a.getY() * a.getY());
    // angle = atan2(y,x)
    double angle = Math.atan2(a.getY(), a.getX());
    result.getCoordinates().add(CoordpolarNodeFactory.createASTCoordinate(d, angle));
}
Example 67
Project: multibit-hd-master  File: NumbersTest.java View source code
/**
   * @param locale The locale providing the language and decimal configuration
   */
private void setConfigurationLocale(Locale locale) {
    Configurations.currentConfiguration.getLanguage().setLocale(locale);
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
    Configurations.currentConfiguration.getBitcoin().setDecimalSeparator(String.valueOf(symbols.getDecimalSeparator()));
    Configurations.currentConfiguration.getBitcoin().setGroupingSeparator(String.valueOf(symbols.getGroupingSeparator()));
}
Example 68
Project: multibit-master  File: Localiser.java View source code
public void setLocale(Locale locale) {
    String propertyFilename = MULTIBIT_RESOURCE_BUNDLE_DIRECTORY + "/" + locale.getLanguage() + "/" + MULTIBIT_RESOURCE_BUNDLE_NAME + PROPERTY_NAME_SUFFIX;
    String propertyFilenameBase = MULTIBIT_RESOURCE_BUNDLE_DIRECTORY + "/" + FALLBACK_LANGUAGE_CODE + "/" + MULTIBIT_RESOURCE_BUNDLE_NAME + PROPERTY_NAME_SUFFIX;
    if ("he".equals(locale.getLanguage()) || "iw".equals(locale.getLanguage())) {
        // Hebrew can be he or iw
        this.locale = new Locale("iw");
        propertyFilename = MULTIBIT_RESOURCE_BUNDLE_DIRECTORY + "/he/" + MULTIBIT_RESOURCE_BUNDLE_NAME + PROPERTY_NAME_SUFFIX;
    }
    if ("id".equals(locale.getLanguage()) || "in".equals(locale.getLanguage())) {
        // Indonesian can be id or in
        this.locale = new Locale("in");
        propertyFilename = MULTIBIT_RESOURCE_BUNDLE_DIRECTORY + "/id/" + MULTIBIT_RESOURCE_BUNDLE_NAME + PROPERTY_NAME_SUFFIX;
    } else {
        this.locale = locale;
    }
    formatter.setLocale(locale);
    numberFormat = NumberFormat.getInstance(locale);
    numberFormat.setMaximumFractionDigits(NUMBER_OF_FRACTION_DIGITS_FOR_BITCOIN);
    decimalFormatSymbols = new java.text.DecimalFormatSymbols(locale);
    boolean foundIt = false;
    try {
        InputStream inputStream = Localiser.class.getResourceAsStream(propertyFilename);
        if (inputStream != null) {
            resourceBundle = new PropertyResourceBundle(new InputStreamReader(inputStream, "UTF8"));
            foundIt = true;
        }
    } catch (FileNotFoundException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    if (!foundIt) {
        // just get the base version i.e. English
        try {
            InputStream inputStream = Localiser.class.getResourceAsStream(propertyFilenameBase);
            if (inputStream != null) {
                resourceBundle = new PropertyResourceBundle(new InputStreamReader(inputStream, "UTF8"));
            }
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
Example 69
Project: oceano-master  File: Slf4jMavenTransferListener.java View source code
@Override
public void transferSucceeded(TransferEvent event) {
    TransferResource resource = event.getResource();
    long contentLength = event.getTransferredBytes();
    if (contentLength >= 0) {
        String type = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
        String len = contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B";
        String throughput = "";
        long duration = System.currentTimeMillis() - resource.getTransferStartTime();
        if (duration > 0) {
            DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH));
            double kbPerSec = (contentLength / 1024.0) / (duration / 1000.0);
            throughput = " at " + format.format(kbPerSec) + " KB/sec";
        }
        out.info(type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len + throughput + ")");
    }
}
Example 70
Project: openmuc-master  File: IESDataFormatUtils.java View source code
// private final static Logger logger = LoggerFactory.getLogger(IESDataFormatUtils.class);
/**
     * Convert a double value into a string with the maximal allowed length of maxlength.
     * 
     * @param value
     *            the value to convert
     * @param maxLength
     *            The maximal allowed length with all signs.
     * @return a double as string with max length.
     * @throws WrongScalingException
     *             will thrown if converted value is bigger then maxLength
     */
public static String convertDoubleToStringWithMaxLength(double value, int maxLength) throws WrongScalingException {
    String ret;
    String format;
    double valueWork = value;
    long lValue = (long) (valueWork * 10000.0);
    valueWork = lValue / 10000.0;
    if (lValue >= 0) {
        if (lValue >> 63 != 0) {
            valueWork *= -1l;
        }
        format = '+' + getFormat(valueWork);
    } else {
        format = getFormat(valueWork);
    }
    DecimalFormat df = new DecimalFormat(format, new DecimalFormatSymbols(Locale.ENGLISH));
    ret = df.format(valueWork);
    if (ret.length() > maxLength) {
        throw new WrongScalingException("Double value (" + value + ") too large for convertion into max length " + maxLength + "! Try to scale value.");
    }
    return ret;
}
Example 71
Project: qpid-jms-master  File: TimeUtils.java View source code
/**
     * Prints the duration in a human readable format as X days Y hours Z minutes etc.
     *
     * @param uptime
     *        the uptime in millis
     * @return the time used for displaying on screen or in logs
     */
public static String printDuration(double uptime) {
    NumberFormat fmtI = new DecimalFormat("###,###", new DecimalFormatSymbols(Locale.ENGLISH));
    NumberFormat fmtD = new DecimalFormat("###,##0.000", new DecimalFormatSymbols(Locale.ENGLISH));
    uptime /= 1000;
    if (uptime < 60) {
        return fmtD.format(uptime) + " seconds";
    }
    uptime /= 60;
    if (uptime < 60) {
        long minutes = (long) uptime;
        String s = fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
        return s;
    }
    uptime /= 60;
    if (uptime < 24) {
        long hours = (long) uptime;
        long minutes = (long) ((uptime - hours) * 60);
        String s = fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
        if (minutes != 0) {
            s += " " + fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
        }
        return s;
    }
    uptime /= 24;
    long days = (long) uptime;
    long hours = (long) ((uptime - days) * 24);
    String s = fmtI.format(days) + (days > 1 ? " days" : " day");
    if (hours != 0) {
        s += " " + fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
    }
    return s;
}
Example 72
Project: seasar2-master  File: DecimalFormatUtil.java View source code
/**
     * 数値�文字列��表記をグルーピングセパレータを削除���数点を.��ら���標準形�正�化���。
     * 
     * @param s
     * @param locale
     * @return 正�化�れ�文字列
     */
public static String normalize(String s, Locale locale) {
    if (s == null) {
        return null;
    }
    DecimalFormatSymbols symbols = DecimalFormatSymbolsUtil.getDecimalFormatSymbols(locale);
    char decimalSep = symbols.getDecimalSeparator();
    char groupingSep = symbols.getGroupingSeparator();
    StringBuffer buf = new StringBuffer(20);
    for (int i = 0; i < s.length(); ++i) {
        char c = s.charAt(i);
        if (c == groupingSep) {
            continue;
        } else if (c == decimalSep) {
            c = '.';
        }
        buf.append(c);
    }
    return buf.toString();
}
Example 73
Project: sos-importer-master  File: n52Utils.java View source code
public static Double parseDouble(final String text) {
    final DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
    Number n;
    final DecimalFormat formatter = new DecimalFormat();
    formatter.setDecimalFormatSymbols(symbols);
    try {
        n = formatter.parse(text);
        return n.doubleValue();
    } catch (final ParseException e) {
        logger.error(String.format("Exception thrown: %s", e.getMessage()), e);
    }
    return null;
}
Example 74
Project: structr-master  File: NumberFormatFunction.java View source code
@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
    if (sources == null || sources.length != 3 || sources[1] == null || sources[2] == null) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    }
    if (arrayHasLengthAndAllElementsNotNull(sources, 3)) {
        try {
            final Double val = Double.parseDouble(sources[0].toString());
            final String langCode = sources[1].toString();
            final String pattern = sources[2].toString();
            return new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(Locale.forLanguageTag(langCode))).format(val);
        } catch (Throwable t) {
            logException(caller, t, sources);
        }
        logParameterError(caller, sources, ctx.isJavaScriptContext());
    }
    return "";
}
Example 75
Project: swj-master  File: ReportStatsTab.java View source code
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (DEBUG_FLAG)
        Log.v(APP_NAME, "ReportStatsTab :: onCreateView()");
    if (getActivity() == null) {
        Log.e(APP_NAME, "ReportStatsTab :: onCreateView() failed since no atcivity is attached");
        throw new IllegalStateException("fragment is not attached to any activity");
    }
    View rootView = inflater.inflate(R.layout.fragment_ex_stats, container, false);
    Bundle exBundle = getArguments();
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols();
    otherSymbols.setDecimalSeparator('.');
    DecimalFormat df = new DecimalFormat("#.##", otherSymbols);
    ((TextView) rootView.findViewById(R.id.exercise_name_in_report)).setText(exBundle.getString("exName"));
    ((TextView) rootView.findViewById(R.id.oneRepMaxWeightNum)).setText(String.valueOf(df.format(exBundle.getDouble("wOneRepMax"))));
    ((TextView) rootView.findViewById(R.id.oneRepAvgWeightNum)).setText(String.valueOf(df.format(exBundle.getDouble("wOneRepAvg"))));
    ((TextView) rootView.findViewById(R.id.oneSetMaxWeightNum)).setText(String.valueOf(df.format(exBundle.getDouble("wOneSetMax"))));
    ((TextView) rootView.findViewById(R.id.oneSetAvgWeightNum)).setText(String.valueOf(df.format(exBundle.getDouble("wOneSetAvg"))));
    ((TextView) rootView.findViewById(R.id.oneDayMaxWeightNum)).setText(String.valueOf(df.format(exBundle.getDouble("wOneDayMax"))));
    ((TextView) rootView.findViewById(R.id.oneDayAvgWeightNum)).setText(String.valueOf(df.format(exBundle.getDouble("wOneDayAvg"))));
    ((TextView) rootView.findViewById(R.id.allTimeMaxWeightNum)).setText(String.valueOf(df.format(exBundle.getDouble("wTotal"))));
    return rootView;
}
Example 76
Project: TwoFactorBtcWallet-master  File: Localiser.java View source code
public void setLocale(Locale locale) {
    String propertyFilename = MULTIBIT_RESOURCE_BUNDLE_DIRECTORY + "/" + locale.getLanguage() + "/" + MULTIBIT_RESOURCE_BUNDLE_NAME + PROPERTY_NAME_SUFFIX;
    String propertyFilenameBase = MULTIBIT_RESOURCE_BUNDLE_DIRECTORY + "/" + FALLBACK_LANGUAGE_CODE + "/" + MULTIBIT_RESOURCE_BUNDLE_NAME + PROPERTY_NAME_SUFFIX;
    if ("he".equals(locale.getLanguage()) || "iw".equals(locale.getLanguage())) {
        // Hebrew can be he or iw
        this.locale = new Locale("iw");
        propertyFilename = MULTIBIT_RESOURCE_BUNDLE_DIRECTORY + "/he/" + MULTIBIT_RESOURCE_BUNDLE_NAME + PROPERTY_NAME_SUFFIX;
    }
    if ("id".equals(locale.getLanguage()) || "in".equals(locale.getLanguage())) {
        // Indonesian can be id or in
        this.locale = new Locale("in");
        propertyFilename = MULTIBIT_RESOURCE_BUNDLE_DIRECTORY + "/id/" + MULTIBIT_RESOURCE_BUNDLE_NAME + PROPERTY_NAME_SUFFIX;
    } else {
        this.locale = locale;
    }
    formatter.setLocale(locale);
    numberFormat = NumberFormat.getInstance(locale);
    numberFormat.setMaximumFractionDigits(NUMBER_OF_FRACTION_DIGITS_FOR_BITCOIN);
    decimalFormatSymbols = new java.text.DecimalFormatSymbols(locale);
    boolean foundIt = false;
    try {
        InputStream inputStream = Localiser.class.getResourceAsStream(propertyFilename);
        if (inputStream != null) {
            resourceBundle = new PropertyResourceBundle(new InputStreamReader(inputStream, "UTF8"));
            foundIt = true;
        }
    } catch (FileNotFoundException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    if (!foundIt) {
        // just get the base version i.e. English
        try {
            InputStream inputStream = Localiser.class.getResourceAsStream(propertyFilenameBase);
            if (inputStream != null) {
                resourceBundle = new PropertyResourceBundle(new InputStreamReader(inputStream, "UTF8"));
            }
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
Example 77
Project: vaadin-master  File: TextFieldWithPropertyFormatter.java View source code
@Override
protected void setup() {
    /*
         * Formatter that: - formats in UK currency style - scales to 2 fraction
         * digits - rounds half up
         */
    // Property containing BigDecimal
    property = new Property<BigDecimal>() {

        private BigDecimal value;

        @Override
        public BigDecimal getValue() {
            return value;
        }

        @Override
        public void setValue(BigDecimal newValue) throws ReadOnlyException {
            value = newValue;
        }

        @Override
        public Class<BigDecimal> getType() {
            return BigDecimal.class;
        }

        @Override
        public boolean isReadOnly() {
            return false;
        }

        @Override
        public void setReadOnly(boolean newStatus) {
        // ignore
        }
    };
    formatter = new PropertyFormatter<BigDecimal>(property) {

        private final DecimalFormat df = new DecimalFormat("#,##0.00", new DecimalFormatSymbols(new Locale("en", "UK")));

        {
            df.setParseBigDecimal(true);
        // df.setRoundingMode(RoundingMode.HALF_UP);
        }

        @Override
        public String format(BigDecimal value) {
            final String retVal;
            if (value == null) {
                retVal = "";
            } else {
                retVal = df.format(value);
            }
            return retVal;
        }

        @Override
        public BigDecimal parse(String formattedValue) throws Exception {
            if (formattedValue != null && formattedValue.trim().length() != 0) {
                BigDecimal value = (BigDecimal) df.parse(formattedValue);
                value = value.setScale(2, BigDecimal.ROUND_HALF_UP);
                return value;
            }
            return null;
        }
    };
    final TextField tf1 = new TextField();
    tf1.setPropertyDataSource(formatter);
    addComponent(tf1);
    Button b = new Button("Sync (typing 12345.6789 and clicking this should format field)");
    b.addClickListener(new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
        }
    });
    addComponent(b);
    b = new Button("Set '12345.6789' to textfield on the server side");
    b.addClickListener(new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            tf1.setValue("12345.6789");
        }
    });
    addComponent(b);
}
Example 78
Project: VarexJ-master  File: DecimalFormatTest.java View source code
@Test
public void testParseDouble() {
    if (verifyNoPropertyViolation()) {
        DecimalFormatSymbols dfs = new DecimalFormatSymbols();
        DecimalFormat dFormat = new DecimalFormat();
        ParsePosition ps = new ParsePosition(0);
        Number nb = dFormat.parse("10" + dfs.getDecimalSeparator() + "10", ps);
        assertTrue(nb instanceof Double);
        assertTrue(nb.doubleValue() == 10.10d);
        assertTrue(ps.getErrorIndex() == -1);
        assertTrue(ps.getIndex() == 5);
    }
}
Example 79
Project: activemq-artemis-master  File: TimeUtils.java View source code
/**
    * Prints the duration in a human readable format as X days Y hours Z minutes etc.
    *
    * @param uptime the uptime in millis
    * @return the time used for displaying on screen or in logs
    */
public static String printDuration(double uptime) {
    // Code taken from Karaf
    // https://svn.apache.org/repos/asf/karaf/trunk/shell/commands/src/main/java/org/apache/karaf/shell/commands/impl/InfoAction.java
    NumberFormat fmtI = new DecimalFormat("###,###", new DecimalFormatSymbols(Locale.ENGLISH));
    NumberFormat fmtD = new DecimalFormat("###,##0.000", new DecimalFormatSymbols(Locale.ENGLISH));
    uptime /= 1000;
    if (uptime < 60) {
        return fmtD.format(uptime) + " seconds";
    }
    uptime /= 60;
    if (uptime < 60) {
        long minutes = (long) uptime;
        String s = fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
        return s;
    }
    uptime /= 60;
    if (uptime < 24) {
        long hours = (long) uptime;
        long minutes = (long) ((uptime - hours) * 60);
        String s = fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
        if (minutes != 0) {
            s += " " + fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
        }
        return s;
    }
    uptime /= 24;
    long days = (long) uptime;
    long hours = (long) ((uptime - days) * 24);
    String s = fmtI.format(days) + (days > 1 ? " days" : " day");
    if (hours != 0) {
        s += " " + fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
    }
    return s;
}
Example 80
Project: aether-demo-master  File: ConsoleTransferListener.java View source code
@Override
public void transferSucceeded(TransferEvent event) {
    transferCompleted(event);
    TransferResource resource = event.getResource();
    long contentLength = event.getTransferredBytes();
    if (contentLength >= 0) {
        String type = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
        String len = contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B";
        String throughput = "";
        long duration = System.currentTimeMillis() - resource.getTransferStartTime();
        if (duration > 0) {
            long bytes = contentLength - resource.getResumeOffset();
            DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH));
            double kbPerSec = (bytes / 1024.0) / (duration / 1000.0);
            throughput = " at " + format.format(kbPerSec) + " KB/sec";
        }
        out.println(type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len + throughput + ")");
    }
}
Example 81
Project: android-oss-master  File: NumberUtils.java View source code
/**
   * Return a formatter that can output an appropriate number based on the input currency and locale.
   */
@NonNull
private static NumberFormat numberFormat(@NonNull final NumberOptions options, @NonNull final Locale locale) {
    final NumberFormat numberFormat;
    if (options.isCurrency()) {
        final DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
        final DecimalFormatSymbols symbols = decimalFormat.getDecimalFormatSymbols();
        symbols.setCurrencySymbol(options.currencySymbol());
        decimalFormat.setDecimalFormatSymbols(symbols);
        numberFormat = decimalFormat;
    } else {
        numberFormat = NumberFormat.getInstance(locale);
    }
    return numberFormat;
}
Example 82
Project: archiva-master  File: ArtifactBuilder.java View source code
public Artifact build() {
    ArtifactReference ref = new ArtifactReference();
    ref.setArtifactId(artifactMetadata.getProject());
    ref.setGroupId(artifactMetadata.getNamespace());
    ref.setVersion(artifactMetadata.getVersion());
    String type = null, classifier = null;
    MavenArtifactFacet facet = (MavenArtifactFacet) artifactMetadata.getFacet(MavenArtifactFacet.FACET_ID);
    if (facet != null) {
        type = facet.getType();
        classifier = facet.getClassifier();
    }
    ref.setClassifier(classifier);
    ref.setType(type);
    File file = managedRepositoryContent.toFile(ref);
    String extension = getExtensionFromFile(file);
    Artifact artifact = new Artifact(ref.getGroupId(), ref.getArtifactId(), ref.getVersion());
    artifact.setRepositoryId(artifactMetadata.getRepositoryId());
    artifact.setClassifier(classifier);
    artifact.setPackaging(type);
    artifact.setType(type);
    artifact.setFileExtension(extension);
    artifact.setPath(managedRepositoryContent.toPath(ref));
    // TODO: find a reusable formatter for this
    double s = this.artifactMetadata.getSize();
    String symbol = "b";
    if (s > 1024) {
        symbol = "K";
        s /= 1024;
        if (s > 1024) {
            symbol = "M";
            s /= 1024;
            if (s > 1024) {
                symbol = "G";
                s /= 1024;
            }
        }
    }
    artifact.setContext(managedRepositoryContent.getId());
    DecimalFormat df = new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.US));
    artifact.setSize(df.format(s) + " " + symbol);
    artifact.setId(ref.getArtifactId() + "-" + ref.getVersion() + "." + ref.getType());
    return artifact;
}
Example 83
Project: AribaWeb-Framework-master  File: DecimalFormatterCommon.java View source code
/**
        Trim the string.  Remove all trailing zero's

        @param str the input string from which leading and trailing whitespace is removed
        @param locale the locale used to determine the decimal separator when trimming whitespace
        @return Returns a input string with after removing leading and trailing whitespace, including trailing zero's.
        @aribaapi documented
    */
public static String trimString(String str, Locale locale) {
    if (StringUtil.nullOrEmptyOrBlankString(str)) {
        return str;
    }
    // Get the decimal separator char
    // Note: The set of symbols returned by BigDecimalFormatter.getDecimalFormatSymbol
    // will work for both DoubleFormatter and BigDecimalFormatter since the only difference
    // between the DecimalFormat objects is the initial isGroupingUsed value.
    DecimalFormatSymbols symbols = BigDecimalFormatter.getDecimalFormatSymbol(locale);
    char decimalSep = symbols.getDecimalSeparator();
    // Search for the decimal separator
    int index = str.indexOf(decimalSep);
    if (index > 0) {
        // Find the first non-zero char.
        int lastIndex = str.length() - 1;
        for (int i = lastIndex; i >= index; i--) {
            if (str.charAt(i) != '0') {
                if (str.charAt(i) == decimalSep) {
                    str = str.substring(0, i);
                } else if (i < lastIndex) {
                    str = str.substring(0, i + 1);
                }
                break;
            }
        }
    }
    return str;
}
Example 84
Project: asakusafw-master  File: FloatOptionFieldAdapterTest.java View source code
/**
     * w/ number format.
     */
@Test
public void number_format() {
    DecimalFormatSymbols syms = DecimalFormatSymbols.getInstance();
    FloatOptionFieldAdapter adapter = FloatOptionFieldAdapter.builder().withNumberFormat("0.00").withDecimalFormatSymbols(syms).build();
    checkParse(adapter, 0, new FloatOption(0));
    checkParse(adapter, 1, new FloatOption(1));
    checkParse(adapter, -1, new FloatOption(-1));
    checkParse(adapter, "-0", new FloatOption(0));
    checkParse(adapter, syms.getNaN(), new FloatOption(Float.NaN));
    checkParse(adapter, syms.getInfinity(), new FloatOption(Float.POSITIVE_INFINITY));
    checkParse(adapter, "-" + syms.getInfinity(), new FloatOption(Float.NEGATIVE_INFINITY));
    checkMalformed(adapter, "", new FloatOption());
    checkMalformed(adapter, "Hello, world!", new FloatOption());
    checkEmit(adapter, new FloatOption(1), "1.00");
    checkEmit(adapter, new FloatOption(-1), "-1.00");
    checkEmit(adapter, new FloatOption((float) Math.PI), "3.14");
    checkEmit(adapter, new FloatOption(12345), "12345.00");
    checkEmit(adapter, new FloatOption(-0), "0.00");
    checkEmit(adapter, new FloatOption(Float.NaN), syms.getNaN());
    checkEmit(adapter, new FloatOption(Float.POSITIVE_INFINITY), syms.getInfinity());
    checkEmit(adapter, new FloatOption(Float.NEGATIVE_INFINITY), "-" + syms.getInfinity());
}
Example 85
Project: awesome-game-store-master  File: GameSystem.java View source code
/**
	 * Formats the money int into currency format. It prints the money with a "$" symbol in front of it.
	 * @param money
	 * @param showCurrencySymbol
	 * @return
	 */
public static String printMoney(int money, boolean showSign) {
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    DecimalFormatSymbols decimalFormatSymbols = ((DecimalFormat) nf).getDecimalFormatSymbols();
    decimalFormatSymbols.setCurrencySymbol("");
    ((DecimalFormat) nf).setDecimalFormatSymbols(decimalFormatSymbols);
    if (showSign) {
        return "$ " + nf.format((float) money / 100).trim();
    }
    return nf.format((float) money / 100).trim();
}
Example 86
Project: bnd-master  File: ConsoleTransferListener.java View source code
@Override
public void transferSucceeded(TransferEvent event) {
    transferCompleted(event);
    TransferResource resource = event.getResource();
    long contentLength = event.getTransferredBytes();
    if (contentLength >= 0) {
        String type = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
        String len = contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B";
        String throughput = "";
        long duration = System.currentTimeMillis() - resource.getTransferStartTime();
        if (duration > 0) {
            long bytes = contentLength - resource.getResumeOffset();
            DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH));
            double kbPerSec = (bytes / 1024.0) / (duration / 1000.0);
            throughput = " at " + format.format(kbPerSec) + " KB/sec";
        }
        out.println(type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len + throughput + ")");
    }
}
Example 87
Project: build-monitor-master  File: ConsoleTransferListener.java View source code
@Override
public void transferSucceeded(TransferEvent event) {
    transferCompleted(event);
    TransferResource resource = event.getResource();
    long contentLength = event.getTransferredBytes();
    if (contentLength >= 0) {
        String type = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
        String len = contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B";
        String throughput = "";
        long duration = System.currentTimeMillis() - resource.getTransferStartTime();
        if (duration > 0) {
            long bytes = contentLength - resource.getResumeOffset();
            DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH));
            double kbPerSec = (bytes / 1024.0) / (duration / 1000.0);
            throughput = " at " + format.format(kbPerSec) + " KB/sec";
        }
        out.println(type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len + throughput + ")");
    }
}
Example 88
Project: CellBots-master  File: Util.java View source code
public static String formatNumber(double number, int decimals) {
    double multiplier = Math.pow(10, decimals);
    number = number * multiplier;
    long inumber = Math.round(number);
    DecimalFormat df = new DecimalFormat();
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setGroupingSeparator(',');
    df.setDecimalFormatSymbols(dfs);
    df.setMaximumFractionDigits(2);
    return df.format(inumber / multiplier);
}
Example 89
Project: cyclos-master  File: NumberConverter.java View source code
public T valueOf(String string) {
    if (StringUtils.isEmpty(string)) {
        return null;
    }
    final DecimalFormatSymbols symbols = numberFormat.getDecimalFormatSymbols();
    final char minusSign = symbols.getMinusSign();
    final char decimalSeparator = symbols.getDecimalSeparator();
    final char groupingSeparator = symbols.getGroupingSeparator();
    boolean negativeNumber = false;
    if (string.indexOf(minusSign) > -1) {
        string = StringUtils.replace(string, String.valueOf(minusSign), "");
        negativeNumber = true;
    }
    final String[] parts = StringUtils.split(string, String.valueOf(decimalSeparator));
    final String integerPart = StringUtils.replace(parts[0], String.valueOf(groupingSeparator), "");
    final boolean hasDecimalPart = parts.length > 1;
    final String decimalPart = hasDecimalPart ? parts[1] : "";
    String bigDecimalString = integerPart;
    if (hasDecimalPart) {
        bigDecimalString = bigDecimalString + "." + decimalPart;
    }
    if (negativeNumber) {
        bigDecimalString = "-" + bigDecimalString;
    }
    final BigDecimal bigDecimal = new BigDecimal(bigDecimalString);
    T value = CoercionHelper.coerce(numberType, bigDecimal);
    if (negativeToAbsoluteValue && value != null && value.floatValue() < 0) {
        value = CoercionHelper.coerce(numberType, -value.floatValue());
    }
    return value;
}
Example 90
Project: freemarker-old-master  File: JavaTemplateNumberFormatFactory.java View source code
@Override
public TemplateNumberFormat get(String params, Locale locale, Environment env) throws InvalidFormatParametersException {
    CacheKey cacheKey = new CacheKey(params, locale);
    NumberFormat jFormat = GLOBAL_FORMAT_CACHE.get(cacheKey);
    if (jFormat == null) {
        if ("number".equals(params)) {
            jFormat = NumberFormat.getNumberInstance(locale);
        } else if ("currency".equals(params)) {
            jFormat = NumberFormat.getCurrencyInstance(locale);
        } else if ("percent".equals(params)) {
            jFormat = NumberFormat.getPercentInstance(locale);
        } else if ("computer".equals(params)) {
            jFormat = env.getCNumberFormat();
        } else {
            try {
                jFormat = new DecimalFormat(params, new DecimalFormatSymbols(locale));
            } catch (IllegalArgumentException e) {
                String msg = e.getMessage();
                throw new InvalidFormatParametersException(msg != null ? msg : "Invalid DecimalFormat pattern", e);
            }
        }
        if (GLOBAL_FORMAT_CACHE.size() >= LEAK_ALERT_NUMBER_FORMAT_CACHE_SIZE) {
            boolean triggered = false;
            synchronized (JavaTemplateNumberFormatFactory.class) {
                if (GLOBAL_FORMAT_CACHE.size() >= LEAK_ALERT_NUMBER_FORMAT_CACHE_SIZE) {
                    triggered = true;
                    GLOBAL_FORMAT_CACHE.clear();
                }
            }
            if (triggered) {
                LOG.warn("Global Java NumberFormat cache has exceeded " + LEAK_ALERT_NUMBER_FORMAT_CACHE_SIZE + " entries => cache flushed. " + "Typical cause: Some template generates high variety of format pattern strings.");
            }
        }
        NumberFormat prevJFormat = GLOBAL_FORMAT_CACHE.putIfAbsent(cacheKey, jFormat);
        if (prevJFormat != null) {
            jFormat = prevJFormat;
        }
    }
    // if cache miss
    // JFormat-s aren't thread-safe; must clone it
    jFormat = (NumberFormat) jFormat.clone();
    return new JavaTemplateNumberFormat(jFormat, params);
}
Example 91
Project: geotools-master  File: FilterFunction_numberFormat2.java View source code
public Object evaluate(Object feature) {
    String format;
    Double number;
    try {
        // attempt to get value and perform conversion
        format = getExpression(0).evaluate(feature, String.class);
    } catch (// probably a type error
    Exception // probably a type error
    e) {
        throw new IllegalArgumentException("Filter Function problem for function dateFormat argument #0 - expected type String");
    }
    try {
        // attempt to get value and perform conversion
        number = getExpression(1).evaluate(feature, Double.class);
    } catch (// probably a type error
    Exception // probably a type error
    e) {
        throw new IllegalArgumentException("Filter Function problem for function dateFormat argument #1 - expected type java.util.Double");
    }
    if (format == null || number == null) {
        return null;
    }
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    if (params.size() > 2) {
        Character neg = getExpression(2).evaluate(feature, Character.class);
        symbols.setMinusSign(neg);
    }
    if (params.size() > 3) {
        Character dec = getExpression(3).evaluate(feature, Character.class);
        symbols.setDecimalSeparator(dec);
    }
    if (params.size() > 4) {
        Character grp = getExpression(4).evaluate(feature, Character.class);
        symbols.setGroupingSeparator(grp);
    }
    DecimalFormat numberFormat = new DecimalFormat(format, symbols);
    return numberFormat.format(number);
}
Example 92
Project: hbci4java-master  File: SyntaxFloat.java View source code
/** @brief converts the given number into hbci-float-format

        @param st a double number in string format (with "," or "." as
               decimal delimiter)
        @return a valid hbci-representation of this number (i.e. with ","
                as decimal delimiter and with no trailing zeroes after
                the "0")
     */
private static String double2string(String st) {
    DecimalFormat hbciFormat = new DecimalFormat("0.##");
    DecimalFormatSymbols symbols = hbciFormat.getDecimalFormatSymbols();
    symbols.setDecimalSeparator(',');
    hbciFormat.setDecimalFormatSymbols(symbols);
    hbciFormat.setDecimalSeparatorAlwaysShown(true);
    return hbciFormat.format(HBCIUtils.string2BigDecimal(st));
}
Example 93
Project: heliosearch-master  File: TestMultiValuedNumericRangeQuery.java View source code
/** Tests NumericRangeQuery on a multi-valued field (multiple numeric values per document).
   * This test ensures, that a classical TermRangeQuery returns exactly the same document numbers as
   * NumericRangeQuery (see SOLR-1322 for discussion) and the multiple precision terms per numeric value
   * do not interfere with multiple numeric values.
   */
public void testMultiValuedNRQ() throws Exception {
    Directory directory = newDirectory();
    RandomIndexWriter writer = new RandomIndexWriter(random(), directory, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMaxBufferedDocs(TestUtil.nextInt(random(), 50, 1000)));
    DecimalFormat format = new DecimalFormat("00000000000", new DecimalFormatSymbols(Locale.ROOT));
    int num = atLeast(500);
    for (int l = 0; l < num; l++) {
        Document doc = new Document();
        for (int m = 0, c = random().nextInt(10); m <= c; m++) {
            int value = random().nextInt(Integer.MAX_VALUE);
            doc.add(newStringField("asc", format.format(value), Field.Store.NO));
            doc.add(new IntField("trie", value, Field.Store.NO));
        }
        writer.addDocument(doc);
    }
    IndexReader reader = writer.getReader();
    writer.close();
    IndexSearcher searcher = newSearcher(reader);
    num = atLeast(50);
    for (int i = 0; i < num; i++) {
        int lower = random().nextInt(Integer.MAX_VALUE);
        int upper = random().nextInt(Integer.MAX_VALUE);
        if (lower > upper) {
            int a = lower;
            lower = upper;
            upper = a;
        }
        TermRangeQuery cq = TermRangeQuery.newStringRange("asc", format.format(lower), format.format(upper), true, true);
        NumericRangeQuery<Integer> tq = NumericRangeQuery.newIntRange("trie", lower, upper, true, true);
        TopDocs trTopDocs = searcher.search(cq, 1);
        TopDocs nrTopDocs = searcher.search(tq, 1);
        assertEquals("Returned count for NumericRangeQuery and TermRangeQuery must be equal", trTopDocs.totalHits, nrTopDocs.totalHits);
    }
    reader.close();
    directory.close();
}
Example 94
Project: high-scale-lucene-master  File: TestMultiValuedNumericRangeQuery.java View source code
/** Tests NumericRangeQuery on a multi-valued field (multiple numeric values per document).
   * This test ensures, that a classical TermRangeQuery returns exactly the same document numbers as
   * NumericRangeQuery (see SOLR-1322 for discussion) and the multiple precision terms per numeric value
   * do not interfere with multiple numeric values.
   */
public void testMultiValuedNRQ() throws Exception {
    final Random rnd = newRandom();
    RAMDirectory directory = new RAMDirectory();
    IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, MaxFieldLength.UNLIMITED);
    DecimalFormat format = new DecimalFormat("00000000000", new DecimalFormatSymbols(Locale.US));
    for (int l = 0; l < 5000; l++) {
        Document doc = new Document();
        for (int m = 0, c = rnd.nextInt(10); m <= c; m++) {
            int value = rnd.nextInt(Integer.MAX_VALUE);
            doc.add(new Field("asc", format.format(value), Field.Store.NO, Field.Index.NOT_ANALYZED));
            doc.add(new NumericField("trie", Field.Store.NO, true).setIntValue(value));
        }
        writer.addDocument(doc);
    }
    writer.close();
    Searcher searcher = new IndexSearcher(directory, true);
    for (int i = 0; i < 50; i++) {
        int lower = rnd.nextInt(Integer.MAX_VALUE);
        int upper = rnd.nextInt(Integer.MAX_VALUE);
        if (lower > upper) {
            int a = lower;
            lower = upper;
            upper = a;
        }
        TermRangeQuery cq = new TermRangeQuery("asc", format.format(lower), format.format(upper), true, true);
        NumericRangeQuery<Integer> tq = NumericRangeQuery.newIntRange("trie", lower, upper, true, true);
        TopDocs trTopDocs = searcher.search(cq, 1);
        TopDocs nrTopDocs = searcher.search(tq, 1);
        assertEquals("Returned count for NumericRangeQuery and TermRangeQuery must be equal", trTopDocs.totalHits, nrTopDocs.totalHits);
    }
    searcher.close();
    directory.close();
}
Example 95
Project: ipt-master  File: CoordinateFormatConverter.java View source code
@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
    // The null value is needed to validate in EmlValidator.java class
    if (values[0].length() == 0) {
        return null;
    }
    // The full name of the property which call the method contained in the Map context
    Object coordObject = context.get(ANGLE);
    // validate coordinates in case the action context doesn't work properly.
    if (coordObject == null) {
        throw new TypeConversionException("Invalid decimal number: " + values[0]);
    } else {
        String coordinate = context.get(ANGLE).toString();
        // Assign the values of the range depending the property who calls the method.
        Range<Double> range;
        if (coordinate.equals(CoordinateUtils.LATITUDE)) {
            // The range of the latitude coordinate. (-90,90)
            range = Range.between(CoordinateUtils.MIN_LATITUDE, CoordinateUtils.MAX_LATITUDE);
        } else {
            // The range of the longitude coordinate. (-180,180)
            range = Range.between(CoordinateUtils.MIN_LONGITUDE, CoordinateUtils.MAX_LONGITUDE);
        }
        Double number;
        try {
            // Converts String to double if fails throws a NumberFormatException.
            // If the String contains a comma, a character, it throws the exception.
            number = Double.parseDouble(values[0]);
            // If the value is in the range, returns the double.
            if (range.contains(number)) {
                return number;
            } else {
                throw new TypeConversionException("Invalid decimal number: " + values[0]);
            }
        } catch (NumberFormatException e) {
            DecimalFormatSymbols symbols = new DecimalFormatSymbols();
            symbols.setDecimalSeparator(ALTERNATIVE_DECIMAL_SEPARATOR);
            DecimalFormat decimal = new DecimalFormat(DECIMAL_PATTERN, symbols);
            try {
                number = decimal.parse(values[0]).doubleValue();
                if (range.contains(number)) {
                    return number;
                } else {
                    throw new TypeConversionException("Invalid decimal number: " + values[0]);
                }
            } catch (ParseException e1) {
                throw new TypeConversionException("Invalid decimal number: " + values[0]);
            }
        }
    }
}
Example 96
Project: jagger-master  File: CustomMetricSummaryFetcher.java View source code
@Override
protected Set<SummarySingleDto> fetchData(List<MetricNameDto> metricNames) {
    //custom metric
    Set<Long> taskIds = new HashSet<>();
    Set<String> metricIds = new HashSet<>();
    for (MetricNameDto metricName : metricNames) {
        taskIds.addAll(metricName.getTaskIds());
        metricIds.add(metricName.getMetricName());
    }
    List<Object[]> metrics = new ArrayList<>();
    metrics.addAll(getCustomMetricsDataNewModel(taskIds, metricIds));
    if (metrics.isEmpty()) {
        log.warn("Could not find data for {}", metricNames);
        return Collections.emptySet();
    }
    Map<MetricNameDto, SummarySingleDto> resultMap = new HashMap<>();
    Map<Long, Map<String, MetricNameDto>> mappedMetricDtos = MetricNameUtil.getMappedMetricDtos(metricNames);
    for (Object[] mas : metrics) {
        Number taskDataId = (Number) mas[3];
        String metricId = (String) mas[2];
        MetricNameDto metricNameDto;
        try {
            metricNameDto = mappedMetricDtos.get(taskDataId.longValue()).get(metricId);
            if (metricNameDto == null) {
                // means that we fetched data that we had not wanted to fetch
                continue;
            }
        } catch (NullPointerException e) {
            throw new IllegalArgumentException("could not find appropriate MetricDto : " + taskDataId + " : " + metricId);
        }
        if (!resultMap.containsKey(metricNameDto)) {
            SummarySingleDto metricDto = new SummarySingleDto();
            metricDto.setMetricName(metricNameDto);
            metricDto.setValues(new HashSet<>());
            resultMap.put(metricNameDto, metricDto);
        }
        SummarySingleDto metricDto = resultMap.get(metricNameDto);
        if (mas[0] == null)
            continue;
        SummaryMetricValueDto value = new SummaryMetricValueDto();
        double val = ((Number) mas[0]).doubleValue();
        value.setValue(new DecimalFormat(FormatCalculator.getNumberFormat(val), new DecimalFormatSymbols(Locale.ENGLISH)).format(val));
        value.setSessionId(Long.parseLong((String) mas[1]));
        metricDto.getValues().add(value);
    }
    return new HashSet<>(resultMap.values());
}
Example 97
Project: javamoney-lib-master  File: ItemFormatBuilderTest.java View source code
@Test
public void testAddTokenFormatTokenOfT() throws IOException {
    ItemFormatBuilder<Number> b = new ItemFormatBuilder<Number>(Number.class);
    b.append(new LiteralTokenStyleableItem<Number>("test- "));
    DecimalFormat df = new DecimalFormat("#0.0#");
    DecimalFormatSymbols syms = df.getDecimalFormatSymbols();
    syms.setDecimalSeparator(':');
    df.setDecimalFormatSymbols(syms);
    b.append(new NumberTokenStyleableItem(df).setNumberGroupChars(',', '\'').setNumberGroupSizes(2, 2, 3));
    b.withStyle(new LocalizationContext.Builder(Number.class).build());
    ItemFormat<Number> f = b.build();
    assertNotNull(f);
    assertEquals("test- 12'345'67,89:12", f.format(123456789.123456789d, Locale.FRENCH));
}
Example 98
Project: jenkins-build-monitor-plugin-master  File: ConsoleTransferListener.java View source code
@Override
public void transferSucceeded(TransferEvent event) {
    transferCompleted(event);
    TransferResource resource = event.getResource();
    long contentLength = event.getTransferredBytes();
    if (contentLength >= 0) {
        String type = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
        String len = contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B";
        String throughput = "";
        long duration = System.currentTimeMillis() - resource.getTransferStartTime();
        if (duration > 0) {
            long bytes = contentLength - resource.getResumeOffset();
            DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH));
            double kbPerSec = (bytes / 1024.0) / (duration / 1000.0);
            throughput = " at " + format.format(kbPerSec) + " KB/sec";
        }
        out.println(type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len + throughput + ")");
    }
}
Example 99
Project: jphp-master  File: NumUtils.java View source code
@FastMethod
@Signature({ @Arg("number"), @Arg("pattern"), @Arg(value = "decSep", optional = @Optional(".")), @Arg(value = "groupSep", optional = @Optional(",")) })
public static Memory format(Environment env, Memory... args) {
    try {
        char decSep = args[2].toChar();
        char groupSep = args[3].toChar();
        DecimalFormat decimalFormat;
        if (decSep == '.' && groupSep == ',')
            decimalFormat = new DecimalFormat(args[1].toString(), DEFAULT_DECIMAL_FORMAT_SYMBOLS);
        else {
            DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols();
            formatSymbols.setZeroDigit('0');
            formatSymbols.setDecimalSeparator(decSep);
            formatSymbols.setGroupingSeparator(groupSep);
            decimalFormat = new DecimalFormat(args[1].toString(), formatSymbols);
        }
        return new StringMemory(decimalFormat.format(args[0].toDouble()));
    } catch (IllegalArgumentException e) {
        return Memory.FALSE;
    }
}
Example 100
Project: kaleido-repository-master  File: NumberHelper.java View source code
/**
    * converter from string to number
    * 
    * <pre>
    * assertNull(toNumber(null, Integer.class));
    * assertEquals((Integer) 1234567, toNumber("1 234 567€", Locale.FRANCE, Integer.class));
    * assertEquals((Integer) 1234567, toNumber("$1,234,567", Locale.US, Integer.class));
    * assertEquals((Float) 1234567.89f, toNumber("1 234 567,89€", Locale.FRANCE, Float.class));
    * assertEquals((Float) 1234567.89f, toNumber("$1,234,567.89", Locale.US, Float.class));
    * </pre>
    * 
    * @param <N>
    * @param value value to convert
    * @param locale Locale you want to use
    * @param c Number class you want
    * @return conversion of the string
    * @throws NumberFormatException
    */
@SuppressWarnings("unchecked")
public static <N extends Number> N toNumber(String value, final Locale locale, final Class<N> c) throws NumberFormatException {
    if (value == null) {
        return null;
    }
    if (locale != null) {
        DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
        value = StringHelper.replaceAll(value, String.valueOf(symbols.getGroupingSeparator()), "");
        value = StringHelper.replaceAll(value, symbols.getCurrencySymbol(), "");
        value = StringHelper.replaceAll(value, String.valueOf(symbols.getDecimalSeparator()), ".");
    }
    // space 32
    value = StringHelper.replaceAll(value, " ", "");
    // nbsp 160
    value = StringHelper.replaceAll(value, " ", "");
    value = StringHelper.replaceAll(value, "\n", "");
    value = StringHelper.replaceAll(value, "\t", "");
    value = StringHelper.replaceAll(value, ",", ".");
    value = StringHelper.replaceAll(value, "$", "");
    value = StringHelper.replaceAll(value, "€", "");
    value = StringHelper.replaceAll(value, "£", "");
    if (c.isAssignableFrom(Byte.class)) {
        return (N) Byte.valueOf(value);
    }
    if (c.isAssignableFrom(Short.class)) {
        return (N) Short.valueOf(value);
    }
    if (c.isAssignableFrom(Integer.class)) {
        return (N) Integer.valueOf(value);
    }
    if (c.isAssignableFrom(Long.class)) {
        return (N) Long.valueOf(value);
    }
    if (c.isAssignableFrom(BigInteger.class)) {
        return (N) new BigInteger(value);
    }
    if (c.isAssignableFrom(Float.class)) {
        return (N) Float.valueOf(value);
    }
    if (c.isAssignableFrom(Double.class)) {
        return (N) Double.valueOf(value);
    }
    if (c.isAssignableFrom(BigDecimal.class)) {
        return (N) new BigDecimal(value);
    }
    throw new IllegalArgumentException(c.getName());
}
Example 101
Project: lb-quickfixj-master  File: DoubleConverter.java View source code
static DecimalFormat getDecimalFormat(int padding) {
    if (padding > 14) {
        // FieldConvertError not supported in setDouble methods on Message
        throw new RuntimeError("maximum padding of 14 zeroes is supported: " + padding);
    }
    DecimalFormat[] decimalFormats = threadDecimalFormats.get();
    if (decimalFormats == null) {
        decimalFormats = new DecimalFormat[14];
        threadDecimalFormats.set(decimalFormats);
    }
    DecimalFormat f = decimalFormats[padding];
    if (f == null) {
        StringBuffer buffer = new StringBuffer("0.");
        for (int i = 0; i < padding; i++) {
            buffer.append('0');
        }
        for (int i = padding; i < 14; i++) {
            buffer.append('#');
        }
        f = new DecimalFormat(buffer.toString());
        f.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
        decimalFormats[padding] = f;
    }
    return f;
}