Java Examples for java.text.DecimalFormat

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

Example 1
Project: HCS-Tools-master  File: NumFormatingTests.java View source code
public static void main(String[] args) {
    DecimalFormat formatter = new DecimalFormat("000.###E0");
    // 1.2345E-1
    System.out.println(formatter.format(0.123));
    // 1.2345E-1
    System.out.println(formatter.format(12.123));
    // 1.2345E-1
    System.out.println(formatter.format(123.0));
    // 1.2345E-1
    System.out.println(formatter.format(123.0));
}
Example 2
Project: LyricViewDemo-master  File: TextUtils.java View source code
public static String duration2String(long time) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date(time));
    double minute = calendar.get(Calendar.MINUTE);
    double second = calendar.get(Calendar.SECOND);
    DecimalFormat format = new DecimalFormat("00");
    return format.format(minute) + ":" + format.format(second);
}
Example 3
Project: my-oscgit-android-master  File: FileUtils.java View source code
/**
     * ת»»Îļþ´óС
     *
     * @param fileS
     * @return B/KB/MB/GB
     */
public static String formatFileSize(long fileS) {
    java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
    String fileSizeString = "";
    if (fileS < 1024) {
        fileSizeString = df.format((double) fileS) + "B";
    } else if (fileS < 1048576) {
        fileSizeString = df.format((double) fileS / 1024) + "KB";
    } else if (fileS < 1073741824) {
        fileSizeString = df.format((double) fileS / 1048576) + "MB";
    } else {
        fileSizeString = df.format((double) fileS / 1073741824) + "G";
    }
    return fileSizeString;
}
Example 4
Project: ProcessPuzzleFramework-master  File: CalculateConvert.java View source code
public double convert() {
    TimeUnit from = null;
    TimeUnit to = null;
    Double quantity = null;
    try {
        quantity = new Double(timeQuantity);
    } catch (Exception e) {
    }
    try {
        MeasurementContext measurementContext = UserRequestManager.getInstance().getApplicationContext().getMeasurementContext();
        from = (TimeUnit) measurementContext.findUnitBySymbol(timeunit1);
        to = (TimeUnit) measurementContext.findUnitBySymbol(timeunit2);
        double d = quantity.doubleValue() * from.findConversionRatio(to);
        // 0.9-tol egeszre kerekitunk
        if (Math.abs(Math.rint(d) - d) <= 0.1)
            d = Math.rint(d);
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");
        try {
            return df.parse(df.format(d)).doubleValue();
        } catch (java.text.ParseException e) {
            throw new ProcessPuzzleParseException("??", "Round doubles", e);
        }
    } catch (Exception e) {
        throw new ProcessPuzzleParseException(timeunit1 + "->" + timeunit2, "Converting units", e);
    }
}
Example 5
Project: TLint-master  File: FormatUtil.java View source code
/**
     * 转�文件大�
     *
     * @return B/KB/MB/GB
     */
public static String formatFileSize(long fileS) {
    java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
    String fileSizeString = "";
    if (fileS < 1024) {
        fileSizeString = df.format((double) fileS) + "B";
    } else if (fileS < 1048576) {
        fileSizeString = df.format((double) fileS / 1024) + "KB";
    } else if (fileS < 1073741824) {
        fileSizeString = df.format((double) fileS / 1048576) + "MB";
    } else {
        fileSizeString = df.format((double) fileS / 1073741824) + "G";
    }
    return fileSizeString;
}
Example 6
Project: activemq-in-action-master  File: Listener.java View source code
public void onMessage(Message message) {
    try {
        MapMessage map = (MapMessage) message;
        String stock = map.getString("stock");
        double price = map.getDouble("price");
        double offer = map.getDouble("offer");
        boolean up = map.getBoolean("up");
        DecimalFormat df = new DecimalFormat("#,###,###,##0.00");
        System.out.println(stock + "\t" + df.format(price) + "\t" + df.format(offer) + "\t" + (up ? "up" : "down"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 7
Project: AlgoDS-master  File: Rope1020.java View source code
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    double r = in.nextDouble();
    double x = 0, y = 0, px = 0, py = 0, fx = 0, fy = 0;
    double l = 0;
    for (int i = 0; i < n; i++) {
        x = in.nextDouble();
        y = in.nextDouble();
        if (i == 0) {
            fx = px = x;
            fy = py = y;
        } else {
            l += Math.sqrt(Math.pow(px - x, 2) + Math.pow(py - y, 2));
            px = x;
            py = y;
        }
    }
    l += Math.sqrt(Math.pow(x - fx, 2) + Math.pow(y - fy, 2));
    DecimalFormat f = new DecimalFormat("#.##");
    System.out.println(f.format(l + 2 * r * Math.PI));
}
Example 8
Project: gdl-tools-master  File: OpenEHRNumberFormatTest.java View source code
public void testGetDecimalFormat() {
    DecimalFormat df = OpenEHRNumberFormat.getDecimalFormat();
    assertEquals("12.345", df.format(12.345));
    df = OpenEHRNumberFormat.getDecimalFormat(5);
    assertEquals("12.34500", df.format(12.345));
    assertEquals("12345.00000", df.format(1.2345E4));
    assertEquals("0.00012", df.format(1.2345E-4));
}
Example 9
Project: histogram-master  File: Utils.java View source code
public static Number roundNumber(Number number, DecimalFormat format) {
    /*
     * DecimalFormat.format() produces an IllegalArgumentException if the 
     * input cannot be formatted. We ignore ParseExceptions expecting that
     * any number which can be formatted can also be parsed by DecimalFormat.
     */
    Number formattedNumber = null;
    try {
        formattedNumber = format.parse(format.format(number));
    } catch (ParseException ex) {
    }
    return formattedNumber;
}
Example 10
Project: java_learn-master  File: Listener.java View source code
public void onMessage(Message message) {
    try {
        MapMessage map = (MapMessage) message;
        String stock = map.getString("stock");
        double price = map.getDouble("price");
        double offer = map.getDouble("offer");
        boolean up = map.getBoolean("up");
        DecimalFormat df = new DecimalFormat("#,###,###,##0.00");
        System.out.println(stock + "\t" + df.format(price) + "\t" + df.format(offer) + "\t" + (up ? "up" : "down"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 11
Project: org.nightlabs.jfire.max-master  File: IssueFileAttachmentUtil.java View source code
public static String getFileSizeString(IssueFileAttachment issueFileAttachment) {
    DecimalFormat df = new DecimalFormat("#.##");
    if (issueFileAttachment.getFileSize() < 1024) {
        return df.format((double) issueFileAttachment.getFileSize()) + " bytes";
    } else if (issueFileAttachment.getFileSize() < 1024 * 1024) {
        return df.format((double) issueFileAttachment.getFileSize() / (double) 1024) + " KB";
    } else
        return df.format((double) issueFileAttachment.getFileSize() / (double) (1024 * 1024)) + " MB";
}
Example 12
Project: org.nightlabs.jfire.max.eclipse-master  File: IssueFileAttachmentUtil.java View source code
public static String getFileSizeString(IssueFileAttachment issueFileAttachment) {
    DecimalFormat df = new DecimalFormat("#.##");
    if (issueFileAttachment.getFileSize() < 1024) {
        return df.format((double) issueFileAttachment.getFileSize()) + " bytes";
    } else if (issueFileAttachment.getFileSize() < 1024 * 1024) {
        return df.format((double) issueFileAttachment.getFileSize() / (double) 1024) + " KB";
    } else
        return df.format((double) issueFileAttachment.getFileSize() / (double) (1024 * 1024)) + " MB";
}
Example 13
Project: project-bacon-master  File: NumberLabel.java View source code
public void setValue(double d) {
    if (allowDecimal) {
        formatter = new DecimalFormat("#,###,###,##0.00");
    } else {
        formatter = new DecimalFormat("#,###,###,###");
    }
    setText(formatter.format(d) + suffix);
    //Set font color.
    if (d < 0) {
        setForeground(Color.RED);
    } else {
        setForeground(Color.BLACK);
    }
}
Example 14
Project: ps-scripts-master  File: SaConverter.java View source code
public static void main(String[] args) throws Exception {
    if (args.length > 0) {
        long startTime = System.nanoTime();
        InputParser parser = new InputParser(args[0]);
        parser.parse();
        long estimatedTime = System.nanoTime() - startTime;
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        System.out.println("Conversion  time: " + decimalFormat.format(estimatedTime * 0.000000001) + " sec(s)");
    }
}
Example 15
Project: streaminer-master  File: NumberUtil.java View source code
public static Number roundNumber(Number number, DecimalFormat format) {
    /*
     * DecimalFormat.format() produces an IllegalArgumentException if the 
     * input cannot be formatted. We ignore ParseExceptions expecting that
     * any number which can be formatted can also be parsed by DecimalFormat.
     */
    Number formattedNumber = null;
    try {
        formattedNumber = format.parse(format.format(number));
    } catch (ParseException ex) {
    }
    return formattedNumber;
}
Example 16
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 17
Project: pss-master  File: FormatStyle.java View source code
public String fileSize(String s1) {
    int iPos = 0;
    String s = "";
    StringBuffer sBuf = new StringBuffer();
    try {
        if (s1.trim().compareTo("") == 0) {
            return "";
        }
        //数字太大,JAVA直接写会无法识别,会引起下�比较失败
        long g = Long.parseLong("1099511627776");
        //int i = Integer.parseInt(s1);
        double i = Double.parseDouble(s1);
        if (i <= 0) {
            sBuf.append("");
        } else if (i < 1024) {
            //四�五入
            sBuf.append(i).append(" B");
            iPos = sBuf.lastIndexOf(".00 B");
            if (iPos > 0) {
                sBuf.delete(iPos, sBuf.length() - 2);
            }
        } else if (i < 1024 * 1024) {
            //四�五入
            sBuf.append(new java.text.DecimalFormat(".00").format(i / 1024)).append(" KB");
            iPos = sBuf.lastIndexOf(".00 KB");
            if (iPos > 0) {
                sBuf.delete(iPos, sBuf.length() - 3);
            }
        } else if (i < 1024 * 1024 * 1024) {
            //四�五入
            sBuf.append(new java.text.DecimalFormat(".00").format(i / (1024 * 1024))).append(" M");
            iPos = sBuf.lastIndexOf(".00 M");
            if (iPos > 0) {
                sBuf.delete(iPos, sBuf.length() - 2);
            }
        } else {
            //四�五入
            sBuf.append(new java.text.DecimalFormat(".00").format(i / (1024 * 1024 * 1024))).append(" G");
            iPos = sBuf.lastIndexOf(".00 G");
            if (iPos > 0) {
                sBuf.delete(iPos, sBuf.length() - 2);
            }
        }
    } catch (Exception e) {
        return "";
    }
    return sBuf.toString();
}
Example 18
Project: TerrainSculptor-master  File: NumberFormatter.java View source code
public static String formatScale(String prefix, double scale, boolean precise) {
    if (scale < 0)
        throw new IllegalArgumentException("negative scale");
    if (precise) {
        if (scale > 10000)
            scale = Math.round(scale / 100) * 100;
        else if (scale > 1000)
            scale = Math.round(scale / 10) * 10;
        else if (scale > 100)
            scale = Math.round(scale);
    } else {
        if (scale > 10000)
            scale = Math.round(scale / 1000) * 1000;
        else if (scale > 1000)
            scale = Math.round(scale / 100) * 100;
        else if (scale > 100)
            scale = Math.round(scale / 10) * 10;
    }
    java.text.DecimalFormat scaleFormatter;
    if (scale > 10)
        scaleFormatter = new java.text.DecimalFormat("###,###");
    else if (scale < 1)
        scaleFormatter = new java.text.DecimalFormat("###,###.###");
    else
        scaleFormatter = new java.text.DecimalFormat("###,###.#");
    StringBuffer str = new StringBuffer();
    if (prefix != null) {
        str.append(prefix);
        str.append(":\t");
    }
    str.append("1:");
    str.append(scaleFormatter.format(scale));
    return str.toString();
}
Example 19
Project: TerrainViewer-master  File: NumberFormatter.java View source code
public static String formatScale(String prefix, double scale, boolean precise) {
    if (scale < 0)
        throw new IllegalArgumentException("negative scale");
    if (precise) {
        if (scale > 10000)
            scale = Math.round(scale / 100) * 100;
        else if (scale > 1000)
            scale = Math.round(scale / 10) * 10;
        else if (scale > 100)
            scale = Math.round(scale);
    } else {
        if (scale > 10000)
            scale = Math.round(scale / 1000) * 1000;
        else if (scale > 1000)
            scale = Math.round(scale / 100) * 100;
        else if (scale > 100)
            scale = Math.round(scale / 10) * 10;
    }
    java.text.DecimalFormat scaleFormatter;
    if (scale > 10)
        scaleFormatter = new java.text.DecimalFormat("###,###");
    else if (scale < 1)
        scaleFormatter = new java.text.DecimalFormat("###,###.###");
    else
        scaleFormatter = new java.text.DecimalFormat("###,###.#");
    StringBuffer str = new StringBuffer();
    if (prefix != null) {
        str.append(prefix);
        str.append(":\t");
    }
    str.append("1:");
    str.append(scaleFormatter.format(scale));
    return str.toString();
}
Example 20
Project: android_libcore-master  File: DecimalFormatTest.java View source code
@TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "", method = "formatToCharacterIterator", args = { java.lang.Object.class })
@KnownFailure("formatting numbers with more than ~300 digits doesn't work." + " Also the third test doesn't round the string like the RI does")
public void test_formatToCharacterIterator() throws Exception {
    AttributedCharacterIterator iterator;
    int[] runStarts;
    int[] runLimits;
    String result;
    char current;
    // For BigDecimal with multiplier test.
    DecimalFormat df = new DecimalFormat();
    df.setMultiplier(10);
    iterator = df.formatToCharacterIterator(new BigDecimal("12345678901234567890"));
    result = "123,456,789,012,345,678,900";
    current = iterator.current();
    for (int i = 0; i < result.length(); i++) {
        assertEquals("wrong char @" + i, result.charAt(i), current);
        current = iterator.next();
    }
    // For BigDecimal with multiplier test.
    df = new DecimalFormat();
    df.setMultiplier(-1);
    df.setMaximumFractionDigits(20);
    iterator = df.formatToCharacterIterator(new BigDecimal("1.23456789012345678901"));
    result = "-1.23456789012345678901";
    current = iterator.current();
    for (int i = 0; i < result.length(); i++) {
        assertEquals("wrong char @" + i, result.charAt(i), current);
        current = iterator.next();
    }
    iterator = new DecimalFormat().formatToCharacterIterator(new BigDecimal("1.23456789E1234"));
    runStarts = new int[] { 0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14 };
    runLimits = new int[] { 2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15 };
    // 000,000,000,000....
    result = "12,345,678,900,";
    current = iterator.current();
    for (int i = 0; i < runStarts.length; i++) {
        assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
        assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
        assertEquals("wrong char @" + i, result.charAt(i), current);
        current = iterator.next();
    }
    assertEquals(0, iterator.getBeginIndex());
    assertEquals(1646, iterator.getEndIndex());
    iterator = new DecimalFormat().formatToCharacterIterator(new BigDecimal("1.23456789E301"));
    runStarts = new int[] { 0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14 };
    runLimits = new int[] { 2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15 };
    // 000,000,000,000....
    result = "12,345,678,900,";
    current = iterator.current();
    for (int i = 0; i < runStarts.length; i++) {
        assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
        assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
        assertEquals("wrong char @" + i, result.charAt(i), current);
        current = iterator.next();
    }
    assertEquals(0, iterator.getBeginIndex());
    assertEquals(402, iterator.getEndIndex());
    iterator = new DecimalFormat().formatToCharacterIterator(new BigDecimal("1.2345678E4"));
    runStarts = new int[] { 0, 0, 2, 3, 3, 3, 6, 7, 7, 7 };
    runLimits = new int[] { 2, 2, 3, 6, 6, 6, 7, 10, 10, 10 };
    result = "12,345.678";
    current = iterator.current();
    for (int i = 0; i < runStarts.length; i++) {
        assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
        assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
        assertEquals("wrong char @" + i, result.charAt(i), current);
        current = iterator.next();
    }
    assertEquals(0, iterator.getBeginIndex());
    assertEquals(10, iterator.getEndIndex());
    iterator = new DecimalFormat().formatToCharacterIterator(new BigInteger("123456789"));
    runStarts = new int[] { 0, 0, 0, 3, 4, 4, 4, 7, 8, 8, 8 };
    runLimits = new int[] { 3, 3, 3, 4, 7, 7, 7, 8, 11, 11, 11 };
    result = "123,456,789";
    current = iterator.current();
    for (int i = 0; i < runStarts.length; i++) {
        assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
        assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
        assertEquals("wrong char @" + i, result.charAt(i), current);
        current = iterator.next();
    }
    assertEquals(0, iterator.getBeginIndex());
    assertEquals(11, iterator.getEndIndex());
}
Example 21
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 22
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 23
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 24
Project: robovm-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 25
Project: ap-computer-science-master  File: CO2FromElectricity.java View source code
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    DecimalFormat two = new DecimalFormat(".##");
    ArrayList<Double> electricityArray = new ArrayList<Double>();
    System.out.print("Please input your average monthly electricity bill, without the dollar sign: ");
    electricityArray.add(in.nextDouble());
    System.out.print("\nPlease input the average price, without the dollar sign, per kilowatt hour: ");
    electricityArray.add(in.nextDouble());
    in.close();
    CO2FromElectricityTester construct1 = new CO2FromElectricityTester(electricityArray.get(0), electricityArray.get(1));
    construct1.CO2Emmisions();
    System.out.println("Average Monthly Electricity Bill:      " + two.format(construct1.getBill()));
    System.out.println("Average Monthly Electricity Price:     " + two.format(construct1.getPrice()));
    System.out.println("Annual CO2 Emmisions from Electricity Usage: " + two.format(construct1.getCO2Emmisions()) + " pounds");
}
Example 26
Project: Assignments-master  File: Helper.java View source code
public String toString(double[] coeffs, int degree) {
    DecimalFormat decimalFormat = new DecimalFormat();
    String rezult = "";
    for (int i = degree; i >= 0; i--) {
        if ((coeffs[i] == 0.) && (i > 0)) {
            if (coeffs[i - 1] > 0) {
                if (rezult.length() > 0) {
                    rezult += "+";
                }
            }
            continue;
        } else if (coeffs[i] != 0.) {
            if (i == 0) {
                rezult += decimalFormat.format(coeffs[i]);
            } else if (i == 1) {
                rezult += ((coeffs[i] == 1) ? "" : (coeffs[i] == -1) ? "-" : decimalFormat.format(coeffs[i])) + "x" + ((coeffs[i - 1] > 0) ? "+" : "");
            } else {
                rezult += ((coeffs[i] == 1) ? "" : (coeffs[i] == -1) ? "-" : decimalFormat.format(coeffs[i])) + "x^" + i + ((coeffs[i - 1] > 0) ? "+" : "");
            }
        }
    }
    return rezult;
}
Example 27
Project: deepnighttwo-master  File: AppMainRead.java View source code
/**
     * @param args
     */
public static void main(String[] args) {
    String host = System.getenv("redishost");
    if (host == null || host.trim().length() == 0) {
        host = "127.0.0.1";
    }
    log("Using redis host " + host);
    Jedis jedis = new Jedis(host);
    DecimalFormat df = new DecimalFormat("B000000000");
    String iog = "1";
    int colCount = Integer.parseInt(System.getenv("colCount"));
    log("ColumnCount=" + colCount);
    int asinCount = Integer.parseInt(System.getenv("asinCount"));
    log("asinCount=" + asinCount);
    int perfSize = asinCount * 10000;
    long start = System.nanoTime();
    long used;
    log("::::::::::::Redis Read Perf Test::::::::::::::::");
    for (int i = 0; i < perfSize; i++) {
        String asin = df.format(i);
        if (jedis.hgetAll((asin + ":" + iog).getBytes()).size() != colCount) {
            log("not tip & carton " + asin);
        }
        if (i % 100000 == 0) {
            used = (System.nanoTime() - start);
            log("Time Used=" + used + "ns for " + i + ". each used:" + (used * 1.0 / i));
        }
    }
    used = (System.nanoTime() - start);
    log("Time Used=" + used + "ns for " + perfSize + ". each used:" + (used * 1.0 / perfSize));
}
Example 28
Project: fastjson-master  File: DoubleTest_custom2.java View source code
@SuppressWarnings({ "rawtypes", "unchecked" })
public void test_0() throws Exception {
    Map values = new HashMap();
    Double v = 9.00;
    values.put("double", v);
    SerializeConfig config = new SerializeConfig();
    config.put(Double.class, new DoubleSerializer(new DecimalFormat("###.00")));
    Assert.assertEquals("{\"double\":9.00}", JSON.toJSONString(values, config));
}
Example 29
Project: grammarviz2_src-master  File: CellDoubleRenderer.java View source code
@Override
public void setValue(Object aValue) {
    Object result = aValue;
    if ((aValue != null) && (aValue instanceof Number)) {
        Number numberValue = (Number) aValue;
        NumberFormat formatter = NumberFormat.getNumberInstance();
        DecimalFormat df = (DecimalFormat) formatter;
        df.applyPattern("##0.00000");
        result = df.format(numberValue.doubleValue());
    }
    super.setValue(result);
    super.setHorizontalAlignment(SwingConstants.RIGHT);
}
Example 30
Project: kalendra-java-utils-master  File: TempMain2.java View source code
/**
	 * @param args
	 */
public static void main(String[] args) {
    System.out.println("TempMain2");
    Matrix D;
    Matrix M1;
    Matrix M2;
    DecimalFormat df;
    MatrixSumMatrixMatrix opSum = new MatrixSumMatrixMatrix();
    MatrixMultiplyMatrixMatrix opMult = new MatrixMultiplyMatrixMatrix();
    df = new DecimalFormat("###,##0.0000");
    double[][] d = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    D = new MatrixFull(d);
    M1 = D.copy();
    M2 = new MatrixFull();
    D.show(df, "%13s");
    opSum.sum(D, M1, M2);
    opMult.multiply(D, M1, M2);
    M2.show();
}
Example 31
Project: memcached-master  File: BaseTest.java View source code
public static void printResult(int length, int threads, int repeats, AtomicLong miss, AtomicLong fail, AtomicLong hit, long duration, long total) {
    DecimalFormat df = new DecimalFormat("######0.00");
    double hitRate = ((double) hit.get()) / (hit.get() + miss.get() + fail.get());
    System.out.println("threads=" + threads + ",repeats=" + repeats + ",valueLength=" + length + ",tps=" + total * 1000000000 / duration + ",miss=" + miss.get() + ",fail=" + fail.get() + ",hit=" + hit.get() + ",all=" + total + ",hitRate=" + df.format(hitRate));
}
Example 32
Project: mite8-com-master  File: CutDoubleValue.java View source code
public static double cutDoubleValue(Double value, int num) {
    String dfStr = "#.";
    if (num <= 0) {
        return value;
    } else {
        for (int i = 0; i < num; i++) {
            dfStr = dfStr + "#";
        }
        DecimalFormat df = new DecimalFormat(dfStr);
        try {
            return Double.parseDouble(df.format(value));
        } catch (Exception e) {
        }
    }
    return value;
}
Example 33
Project: ps-framework-master  File: DurationFormatter.java View source code
public static String format(long durationMillis) {
    // calculate
    long hours = TimeUnit.MILLISECONDS.toHours(durationMillis);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(durationMillis) - TimeUnit.HOURS.toMinutes(hours);
    double seconds = (durationMillis - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes)) / 1000.0;
    // print
    StringBuilder formatted = new StringBuilder();
    if (hours > 0) {
        formatted.append(hours + "h");
    }
    if (minutes > 0) {
        formatted.append(minutes + "m");
    }
    if (hours == 0 && seconds != 0) {
        if (minutes > 0) {
            // forget about ms
            formatted.append(new DecimalFormat("##").format(seconds));
        } else if (seconds >= 1) {
            // round 2 digits ms
            formatted.append(new DecimalFormat("##.##").format(seconds));
        } else {
            // all ms
            formatted.append(seconds);
        }
        formatted.append("s");
    }
    return formatted.toString();
}
Example 34
Project: SmartReceiptsLibrary-master  File: DefaultDistanceRatePreference.java View source code
@Override
public CharSequence getSummary() {
    if (//Add a zero check
    TextUtils.isEmpty(getText())) {
        return getContext().getString(R.string.pref_distance_rate_summaryOff);
    } else {
        try {
            float value = Float.parseFloat(getText());
            if (value <= 0) {
                return getContext().getString(R.string.pref_distance_rate_summaryOff);
            }
            DecimalFormat decimalFormat = new DecimalFormat();
            decimalFormat.setMaximumFractionDigits(Distance.RATE_PRECISION);
            decimalFormat.setMinimumFractionDigits(Distance.RATE_PRECISION);
            decimalFormat.setGroupingUsed(false);
            return getContext().getString(R.string.pref_distance_rate_summaryOn, decimalFormat.format(value));
        } catch (NumberFormatException e) {
            return getContext().getString(R.string.pref_distance_rate_summaryOff);
        }
    }
}
Example 35
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 36
Project: superCleanMaster-master  File: TextFormater.java View source code
public static String dataSizeFormat(long size) {
    DecimalFormat formater = new DecimalFormat("####.00");
    if (size < 1024) {
        return size + "byte";
    } else if (//左移20�,相当于1024 * 1024
    size < (1 << 20)) {
        //�移10�,相当于除以1024
        float kSize = size >> 10;
        return formater.format(kSize) + "KB";
    } else if (//左移30�,相当于1024 * 1024 * 1024
    size < (1 << 30)) {
        //�移20�,相当于除以1024�除以1024
        float mSize = size >> 20;
        return formater.format(mSize) + "MB";
    } else if (size < (1 << 40)) {
        float gSize = size >> 30;
        return formater.format(gSize) + "GB";
    } else {
        return "size : error";
    }
}
Example 37
Project: xmemcached-master  File: BaseTest.java View source code
public static void printResult(int length, int threads, int repeats, AtomicLong miss, AtomicLong fail, AtomicLong hit, long duration, long total) {
    DecimalFormat df = new DecimalFormat("######0.00");
    double hitRate = ((double) hit.get()) / (hit.get() + miss.get() + fail.get());
    System.out.println("threads=" + threads + ",repeats=" + repeats + ",valueLength=" + length + ",tps=" + total * 1000000000 / duration + ",miss=" + miss.get() + ",fail=" + fail.get() + ",hit=" + hit.get() + ",all=" + total + ",hitRate=" + df.format(hitRate));
}
Example 38
Project: Xtest-master  File: AllTests.java View source code
@AfterClass
public static void reportTime() {
    long end = System.nanoTime();
    double d = (end - start) / (double) TimeUnit.NANOSECONDS.convert(1, TimeUnit.SECONDS);
    d += XtestJunitRunner.getCumulative();
    DecimalFormat decimalFormat = new DecimalFormat("#.###");
    System.out.println("\n\nAll Tests\n------------\n" + decimalFormat.format(d) + "s");
}
Example 39
Project: YHUtils-master  File: FileUtil.java View source code
/**
     * 获�文件的大�
     *
     * @param fileS
     * @return
     */
public static String FormetFileSize(long fileS) {
    //转�文件大�
    DecimalFormat df = new DecimalFormat("#.00");
    String fileSizeString = "0K";
    if (fileS < 1024) {
        fileSizeString = df.format((double) fileS) + "B";
    } else if (fileS < 1048576) {
        fileSizeString = df.format((double) fileS / 1024) + "K";
    } else if (fileS < 1073741824) {
        fileSizeString = df.format((double) fileS / 1048576) + "M";
    } else {
        fileSizeString = df.format((double) fileS / 1073741824) + "G";
    }
    return fileSizeString;
}
Example 40
Project: cocoon-master  File: FormattingFloatConvertor.java View source code
public Object convertFromString(String value, Locale locale, Convertor.FormatCache formatCache) {
    DecimalFormat decimalFormat = getDecimalFormat(locale, formatCache);
    Number decimalValue;
    try {
        decimalValue = decimalFormat.parse(value);
    } catch (ParseException e) {
        return null;
    }
    if (decimalValue instanceof BigDecimal) {
    // no need for conversion
    } else if (decimalValue instanceof Integer) {
        decimalValue = new BigDecimal(decimalValue.intValue());
    } else if (decimalValue instanceof Long) {
        decimalValue = new BigDecimal(decimalValue.longValue());
    } else if (decimalValue instanceof Double) {
        decimalValue = new BigDecimal(decimalValue.doubleValue());
    } else if (decimalValue instanceof BigInteger) {
        decimalValue = new BigDecimal((BigInteger) decimalValue);
    } else {
        return null;
    }
    return decimalValue;
}
Example 41
Project: DDM-master  File: DecisionMaker.java View source code
/**
	 * Final decision using Weighted Arithmetic Mean
	 * @param dataToPredict
	 * @param decisionResult
	 * @param trainingSize
	 */
private void MakeWAM(DataInstance dataToPredict, HashMap<String, ClassificationResult> decisionResult, int trainingSize) {
    long startTimeMillis = System.currentTimeMillis();
    DecisionRange decisionRange = new DecisionRange();
    double accumulated = 0.0;
    double percentageAccumulated = 0.0;
    String description = "";
    for (int i = 1; i <= decisionResult.size(); i++) {
        ClassificationResult cr = decisionResult.get("Classifier" + i);
        double percentage = cr.getTrainingSize() / (double) trainingSize;
        double prediction = cr.getInstancePredictedValue();
        decisionRange.AddItem(cr.getPredictedInstanceValue(), prediction);
        Classification.AddItem(cr.getPredictedInstanceValue(), prediction);
        accumulated = accumulated + (percentage * prediction);
        percentageAccumulated = percentageAccumulated + percentage;
        java.text.DecimalFormat percentageFormatter = new java.text.DecimalFormat("#0.00");
        String text = percentageFormatter.format(percentage);
        if (// There is no need to generate
        decisionResult.size() > 1)
            // output for only 1 classifier.
            description = description + "\tClassifier" + i + " (" + cr.getType() + ") decision:" + cr.getPredictedInstanceValue() + "(" + text + "%) " + cr.getDuration() + "ms \r\n";
        else
            description = description + "\tClassifier" + i + " (" + cr.getType() + ") " + cr.getDuration() + "ms \r\n";
    }
    double WeightedMean = accumulated / percentageAccumulated;
    String value = decisionRange.testValue(WeightedMean);
    long finishTimeMillis = System.currentTimeMillis();
    long duration = (finishTimeMillis - startTimeMillis);
    try {
        java.text.DecimalFormat percentageFormatter = new java.text.DecimalFormat("#0.00");
        String text = percentageFormatter.format(WeightedMean);
        String disagree = "";
        if (!dataToPredict.getValue().contains(value))
            disagree = " **disagreed";
        bw.write(dataToPredict.getValue().toString() + " \r\n" + description + "\t\tFinal Decision using WAW (" + value + ") value:" + text + " in " + duration + "ms" + disagree + "\r\n");
    } catch (Exception e) {
        e.printStackTrace();
    }
    ;
}
Example 42
Project: jasper-xml-to-pdf-generator-master  File: MoneyUAHDirective.java View source code
public String moneyUAH(String moneyValue) {
    if (moneyValue == null) {
        return "";
    }
    java.text.NumberFormat nf = java.text.NumberFormat.getNumberInstance(java.util.Locale.FRANCE);
    java.text.DecimalFormat df = (java.text.DecimalFormat) nf;
    df.applyPattern(",##0.00");
    return nf.format(new java.math.BigDecimal(moneyValue)) + " грн.";
}
Example 43
Project: osp-master  File: ControlSlider.java View source code
// ------------------------------------------------
// Set and Get the values of the properties
// ------------------------------------------------
public void setValue(int _index, Value _value) {
    switch(_index) {
        case VARIABLE:
            if (internalValue.value != _value.getDouble()) {
                setTheValue(_value.getDouble());
            }
            break;
        case 1:
            defaultValueSet = true;
            defaultValue = _value.getDouble();
            setActive(false);
            reset();
            setActive(true);
            break;
        case 2:
            setMinimum(_value.getDouble());
            break;
        case 3:
            setMaximum(_value.getDouble());
            break;
        case // pressaction
        4:
            //$NON-NLS-1$
            removeAction(ControlSwingElement.ACTION_PRESS, getProperty("pressaction"));
            addAction(ControlSwingElement.ACTION_PRESS, _value.getString());
            break;
        case // dragaction
        5:
            //$NON-NLS-1$
            removeAction(ControlElement.VARIABLE_CHANGED, getProperty("dragaction"));
            addAction(ControlElement.VARIABLE_CHANGED, _value.getString());
            break;
        case // pressaction
        6:
            //$NON-NLS-1$
            removeAction(ControlElement.ACTION, getProperty("action"));
            addAction(ControlElement.ACTION, _value.getString());
            break;
        case 7:
            if (_value.getObject() instanceof java.text.DecimalFormat) {
                if (format == (java.text.DecimalFormat) _value.getObject()) {
                    return;
                }
                format = (java.text.DecimalFormat) _value.getObject();
                titledBorder.setTitle(format.format(internalValue.value));
                slider.setBorder(titledBorder);
            }
            break;
        case 8:
            if (_value.getInteger() != ticks) {
                ticks = _value.getInteger();
                setTicks();
            }
            break;
        case 9:
            if (_value.getObject() instanceof java.text.DecimalFormat) {
                if (ticksFormat == (java.text.DecimalFormat) _value.getObject()) {
                    return;
                }
                ticksFormat = (java.text.DecimalFormat) _value.getObject();
                slider.setPaintLabels(true);
                setTicks();
            }
            break;
        case 10:
            slider.setSnapToTicks(_value.getBoolean());
            break;
        case 11:
            if (slider.getOrientation() != _value.getInteger()) {
                slider.setOrientation(_value.getInteger());
            }
            break;
        default:
            super.setValue(_index - 12, _value);
            break;
    }
}
Example 44
Project: Android-AndroidTV-master  File: TextFormater.java View source code
public static String longtoString(long size) {
    DecimalFormat format = new DecimalFormat("####.00");
    if (size < 1024) {
        return size + "byte";
    } else if (// 左移20�,相当于1024 * 1024
    size < (1 << 20)) {
        // �移10�,相当于除以1024
        float kSize = size >> 10;
        return format.format(kSize) + "KB";
    } else if (// 左移30�,相当于1024 * 1024 * 1024
    size < (1 << 30)) {
        // �移20�,相当于除以1024�除以1024
        float mSize = size >> 20;
        return format.format(mSize) + "MB";
    } else if (size < (1 << 40)) {
        float gSize = size >> 30;
        return format.format(gSize) + "GB";
    } else {
        return "size error";
    }
}
Example 45
Project: android-furk-app-master  File: APIUtils.java View source code
public static String formatSize(String strSize) {
    try {
        long size = Long.parseLong(strSize);
        if (size >= 1073741824) {
            DecimalFormat df = new DecimalFormat("#.#");
            return df.format(size / 1073741824.0) + "GB";
        } else if (size >= 1048576) {
            return Long.toString(size / 1048576) + " MB";
        } else if (size >= 1024) {
            return Long.toString(size / 1024) + " KB";
        } else {
            return Long.toString(size) + " B";
        }
    } catch (NumberFormatException e) {
        return "N/A";
    }
}
Example 46
Project: android-mileage-master  File: ChartDisplay.java View source code
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chart);
    m_chart = (LineChart) findViewById(R.id.chart);
    m_prefs = PreferencesProvider.getInstance(this);
    m_vehicle = new Vehicle(getIntent().getExtras().getLong(VEHICLE_ID));
    m_fillups = m_vehicle.getAllFillUps(m_prefs.getCalculator());
    m_format = new DecimalFormat("0.00");
    buildChart();
}
Example 47
Project: AndroidTVLauncher-master  File: TextFormater.java View source code
public static String longtoString(long size) {
    DecimalFormat format = new DecimalFormat("####.00");
    if (size < 1024) {
        return size + "byte";
    } else if (// 左移20�,相当于1024 * 1024
    size < (1 << 20)) {
        // �移10�,相当于除以1024
        float kSize = size >> 10;
        return format.format(kSize) + "KB";
    } else if (// 左移30�,相当于1024 * 1024 * 1024
    size < (1 << 30)) {
        // �移20�,相当于除以1024�除以1024
        float mSize = size >> 20;
        return format.format(mSize) + "MB";
    } else if (size < (1 << 40)) {
        float gSize = size >> 30;
        return format.format(gSize) + "GB";
    } else {
        return "size error";
    }
}
Example 48
Project: aq2o-master  File: DateConversionTest.java View source code
public void testCreate() throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss.SSS");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String s1 = "20110101 23:59:59.990";
    double dou = 20110101235959.990;
    DecimalFormat dcf = new DecimalFormat("00000000000000.000000000");
    String s3 = dcf.format(dou);
    String shouldBe = "20110101235959.990000000";
    long ms = sdf.parse(s1).getTime();
    Date d1 = new Date(ms);
    String s2 = sdf.format(d1);
    Date8Time6Parser d8t6p = new Date8Time6Parser();
    Double d8t6 = d8t6p.fromMilliseconds(ms);
    assertEquals(shouldBe, d8t6p.toString(d8t6));
}
Example 49
Project: Bob-master  File: TermNumberList.java View source code
protected void setFormatString(String formatString) {
    _formatString = formatString;
    _formatter = new ThreadLocal<DecimalFormat>() {

        protected DecimalFormat initialValue() {
            if (_formatString != null) {
                return new DecimalFormat(_formatString);
            } else {
                return null;
            }
        }
    };
}
Example 50
Project: bobo-master  File: TermNumberList.java View source code
protected void setFormatString(String formatString) {
    _formatString = formatString;
    _formatter = new ThreadLocal<DecimalFormat>() {

        protected DecimalFormat initialValue() {
            if (_formatString != null) {
                return new DecimalFormat(_formatString);
            } else {
                return null;
            }
        }
    };
}
Example 51
Project: chantier-master  File: OutputNumber.java View source code
public DecimalFormat decimal() {
    DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(_requestGlobals.getRequest().getLocale());
    format.setMaximumFractionDigits(2);
    format.setPositiveSuffix("€");
    format.setNegativeSuffix("€");
    format.setDecimalSeparatorAlwaysShown(true);
    format.setMaximumFractionDigits(2);
    format.setMinimumFractionDigits(2);
    return format;
}
Example 52
Project: chartsy-master  File: PriceAxisMarker.java View source code
public static void paint(Graphics2D g, ChartFrame cf, double value, Color color, double y) {
    DecimalFormat df = new DecimalFormat("#,##0.00");
    if (value < 10f) {
        df = new DecimalFormat("#,##0.00000");
    }
    RectangleInsets dataOffset = ChartData.dataOffset;
    FontMetrics fm = g.getFontMetrics();
    g.setPaint(color);
    double x = 1;
    double w = dataOffset.getRight() - 6;
    double h = fm.getHeight() + 4;
    GeneralPath gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, 5);
    gp.moveTo((float) x, (float) y);
    gp.lineTo((float) (x + 6), (float) (y - h / 2));
    gp.lineTo((float) (x + w + 8), (float) (y - h / 2));
    gp.lineTo((float) (x + w + 8), (float) (y + h / 2));
    gp.lineTo((float) (x + 6), (float) (y + h / 2));
    gp.closePath();
    g.fill(gp);
    g.setPaint(new Color(0xffffff));
    g.drawString(df.format(value), (float) (x + 6 + 1), (float) (y + fm.getDescent()));
}
Example 53
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 54
Project: fablab-android-master  File: CartViewModelRenderer.java View source code
@Override
public void render() {
    CartViewModel viewModel = getContent();
    new ViewCommandBinding().bind(getRootView(), viewModel.getCreateProjectFromCartCommand());
    mItemCountTV.setText(Integer.toString(viewModel.getItemCount()));
    mCartPriceTV.setText(new DecimalFormat("00.00").format(viewModel.getCartPrice()));
}
Example 55
Project: gnucash-android-master  File: AmountParser.java View source code
/**
     * Parses {@code amount} and returns it as a BigDecimal.
     *
     * @param amount String with the amount to parse.
     * @return The amount parsed as a BigDecimal.
     * @throws ParseException if the full string couldn't be parsed as an amount.
     */
public static BigDecimal parse(String amount) throws ParseException {
    DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance();
    formatter.setParseBigDecimal(true);
    ParsePosition parsePosition = new ParsePosition(0);
    BigDecimal parsedAmount = (BigDecimal) formatter.parse(amount, parsePosition);
    // Ensure any mistyping by the user is caught instead of partially parsed
    if ((parsedAmount == null) || (parsePosition.getIndex() < amount.length()))
        throw new ParseException("Parse error", parsePosition.getErrorIndex());
    return parsedAmount;
}
Example 56
Project: interval-music-compositor-master  File: FormatTime.java View source code
/**
   * Takes seconds as argument and formats them to for time display ('MM:SS', or 'H:MM:SS' if there are hours).
   * 
   * @param seconds
   *          , a positive number of seconds, if not integer it is rounded.
   * @return the formatted string
   */
public String getStrictFormattedTime(double seconds) {
    int discreteSeconds = (int) Math.abs(seconds);
    String result = "";
    DecimalFormat df = new DecimalFormat(NUMBER_FORMAT);
    if (discreteSeconds < 3600) {
        int minutes = (int) Math.floor(discreteSeconds / 60.0);
        result = df.format(minutes) + ":" + df.format(discreteSeconds - (minutes * 60));
    } else {
        int hours = (int) Math.floor(discreteSeconds / 3600.0);
        int minutes = (int) Math.floor((discreteSeconds - (hours * 3600)) / 60.0);
        result = String.valueOf(hours) + ":" + df.format(minutes) + ":" + df.format(discreteSeconds - (minutes * 60) - (hours * 3600));
    }
    if (seconds < 0) {
        result = SIGN + result;
    }
    return result;
}
Example 57
Project: ismp_manager-master  File: Test.java View source code
/**
	 * @param args
	 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Hello.");
    System.out.println("Long max value: " + Long.MAX_VALUE + " Long min value: " + Long.MIN_VALUE);
    DecimalFormat decimalFormat = new DecimalFormat();
    System.out.println("Double max value: " + decimalFormat.format(Double.MAX_VALUE) + " Long min value: " + Double.MIN_VALUE);
}
Example 58
Project: jif-master  File: TabFormatTest.java View source code
public void testFormatting() {
    DataRow row = new DataRow(new DecimalFormat("###0.########"));
    row.add(1.2d);
    row.add(3);
    row.add(5.7865d);
    row.add(123);
    row.add("Testing... one, two, three");
    String res = fmt.format(row);
    assertEquals("1.2\t3\t5.7865\t123\tTesting... one, two, three", res);
}
Example 59
Project: jMathLib-master  File: DoubleVectorProperty.java View source code
public String toString() {
    if (array.length > 4)
        return ("[ 1 x " + array.length + " array ]");
    else {
        String s = "[ ";
        DecimalFormat fmt = new DecimalFormat("0.0000 ");
        for (int i = 0; i < array.length; i++) s += fmt.format(array[i]);
        s += "]";
        return s;
    }
}
Example 60
Project: kefirbb-master  File: PerformanceStaticTest.java View source code
public static void main(String[] args) throws IOException {
    StringBuilder builder = new StringBuilder();
    Reader reader = new InputStreamReader(new FileInputStream("resource/text.txt"), "utf-8");
    try {
        char[] buf = new char[4096];
        int len;
        while (0 < (len = reader.read(buf))) {
            builder.append(buf, 0, len);
        }
    } finally {
        reader.close();
    }
    String text = builder.toString();
    TextProcessor processor = BBProcessorFactory.getInstance().createFromResource("org/kefirsf/bb/default.xml");
    long start = System.currentTimeMillis();
    String result = processor.process(text);
    long finish = System.currentTimeMillis();
    DecimalFormat format = new DecimalFormat("# ##0");
    System.out.println(MessageFormat.format("Text length: {0} chars.", format.format(text.length())));
    System.out.println(MessageFormat.format("Time: {0} milliseconds.", format.format(finish - start)));
    System.out.println(MessageFormat.format("Result: {0}", result.substring(0, 256)));
}
Example 61
Project: learning-master  File: LoanBean.java View source code
public void summary(LoanApplication app) {
    DecimalFormat df = new DecimalFormat("###,###.00");
    System.out.println("\n======== Loan Intake Summary =========" + "\nSSN           : " + app.getApplicant().getSsn() + "\nLoan Amount   : " + app.getAmount() + "\nLoan Length   : " + app.getLengthYears() + "\nIncome        : " + app.getIncome().getMonthlyAmount() + "\nName          : " + app.getApplicant().getFirstName() + " " + app.getApplicant().getLastName() + "\nAddress       : " + app.getApplicant().getStreetAddress() + "\nPostal Code   : " + app.getApplicant().getPostalCode() + "\nChecking Bal  : " + df.format(app.getApplicant().getCheckingBalance()) + "\nSavings Bal   : " + df.format(app.getApplicant().getSavingsBalance()) + "\n======================================\n");
}
Example 62
Project: mct-master  File: BigLabels.java View source code
public static void main(String[] args) {
    XYPlotFrame frame = new XYPlotFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setup();
    XYAxis xAxis = frame.getXAxis();
    XYAxis yAxis = frame.getYAxis();
    final LinearXYPlotLine line = new LinearXYPlotLine(xAxis, yAxis, XYDimension.X);
    line.setForeground(Color.white);
    final SimpleXYDataset d = new SimpleXYDataset(line);
    d.setMaxCapacity(1000);
    d.setXData(line.getXData());
    d.setYData(line.getYData());
    frame.addPlotLine(line);
    yAxis.setStart(-1.2);
    yAxis.setEnd(1.2);
    xAxis.setStart(0);
    xAxis.setEnd(2 * Math.PI);
    ((LinearXYAxis) xAxis).setFormat(new DecimalFormat("0.0000000"));
    ((LinearXYAxis) yAxis).setFormat(new DecimalFormat("0.0000000"));
    ((LinearXYAxis) yAxis).setLabelRotation(Rotation.CCW);
    for (int x = 0; x <= 100; x++) {
        double x2 = x / 100.0 * 2 * Math.PI;
        double y2 = Math.sin(x2);
        d.add(x2, y2);
    }
    frame.setSize(400, 300);
    frame.setVisible(true);
}
Example 63
Project: MVPAndroidBootstrap-master  File: CountUtil.java View source code
/**
     * Used to format a given number into a short representation.
     * <p/>
     * Examples:
     * Given 9100, will return "9.1k".
     * Given 8100000, will return "8.1m"
     * Given 10, will return 10"
     *
     * @param count Value to convert.
     * @return Formatted value (see examples)
     */
public static String getFormattedCount(Long count) {
    final String unit;
    final Double dbl;
    final DecimalFormat format = new DecimalFormat("#.#");
    if (count < 1000) {
        return format.format(count);
    } else if (count < 1000000) {
        unit = "k";
        dbl = count / 1000.0;
    } else if (count < 1000000000) {
        unit = "m";
        dbl = count / 1000000.0;
    } else {
        unit = "b";
        dbl = count / 1000000000.0;
    }
    return format.format(dbl) + unit;
}
Example 64
Project: OpenCvSample-master  File: FpsMeter.java View source code
public void measure() {
    framesCouner++;
    if (framesCouner % step == 0) {
        long time = Core.getTickCount();
        double fps = step * freq / (time - prevFrameTime);
        prevFrameTime = time;
        DecimalFormat twoPlaces = new DecimalFormat("0.00");
        strfps = twoPlaces.format(fps) + " FPS";
        Log.i(TAG, strfps);
    }
}
Example 65
Project: openmap-master  File: RuleOp.java View source code
public boolean evaluate(Object key, Object val) {
    if (key == null) {
        return compare(-1);
    }
    if (val instanceof Number) {
        if (!(key instanceof Double)) {
            java.text.DecimalFormat df = new java.text.DecimalFormat();
            DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.ENGLISH);
            df.setDecimalFormatSymbols(dfs);
            try {
                key = new Double(df.parse(key.toString()).doubleValue());
            } catch (java.text.ParseException pe) {
                return compare(-1);
            }
        }
        return compare(((Double) key).compareTo(((Number) val).doubleValue()));
    }
    return compare(((String) key.toString()).compareTo(val.toString()));
}
Example 66
Project: p2-installer-master  File: UIUtils.java View source code
/**
	 * Displays the given in a human-readable format.
	 * @param size
	 * @return The formatted string.
	 */
public static String formatBytes(long size) {
    if (size <= 0) {
        //$NON-NLS-1$
        return size + " B";
    }
    //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
    String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
    int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
    //$NON-NLS-1$ //$NON-NLS-2$
    return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
Example 67
Project: poseidon-rest-master  File: DPOrderMapper.java View source code
private DPOrder mapToApi(OrderModel mOrder) {
    DecimalFormat df = new DecimalFormat("#.##");
    df.setRoundingMode(RoundingMode.HALF_UP);
    DPOrder dpOrder = new DPOrder();
    dpOrder.id = mOrder.id;
    String posname = mOrder.position.name;
    String name = mOrder.position_name != null & !mOrder.position_name.isEmpty() ? mOrder.position_name : mOrder.position.name;
    try {
        dpOrder.name = URLEncoder.encode(name, "UTF-8");
        dpOrder.posname = URLEncoder.encode(posname, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new UnsupportedOperationException(e);
    }
    dpOrder.name_dec = name;
    dpOrder.longitude = mOrder.position.longitude;
    dpOrder.latitude = mOrder.position.latitude;
    return dpOrder;
}
Example 68
Project: pysonar2-master  File: FancyProgress.java View source code
public void tick(int n) {
    count += n;
    if (count > total) {
        total = count;
    }
    long elapsed = System.currentTimeMillis() - lastTickTime;
    if (elapsed > 500 || count == total || count % segSize == 0) {
        int len = (int) Math.floor(width * count / total);
        System.out.print("\r[");
        for (int i = 0; i < len; i++) {
            System.out.print("=");
        }
        for (int j = len; j < width; j++) {
            System.out.print(" ");
        }
        System.out.print("]  ");
        System.out.print(Util.percent(count, total) + " (" + count + "/" + total + ")");
        DecimalFormat df = new DecimalFormat("#");
        double rate;
        if (elapsed > 1) {
            rate = (count - lastCount) / (elapsed / 1000.0);
        } else {
            rate = lastRate;
        }
        System.out.print(" " + df.format(rate) + "/s    ");
        lastTickTime = System.currentTimeMillis();
        lastCount = count;
    }
}
Example 69
Project: RxAndroidBootstrap-master  File: CountUtil.java View source code
/**
     * Used to format a given number into a short representation.
     * <p/>
     * Examples:
     * Given 9100, will return "9.1k".
     * Given 8100000, will return "8.1m"
     * Given 10, will return 10"
     *
     * @param count Value to convert.
     * @return Formatted value (see examples)
     */
public static String getFormattedCount(Long count) {
    final String unit;
    final Double dbl;
    final DecimalFormat format = new DecimalFormat("#.#");
    if (count < 1000) {
        return format.format(count);
    } else if (count < 1000000) {
        unit = "k";
        dbl = count / 1000.0;
    } else if (count < 1000000000) {
        unit = "m";
        dbl = count / 1000000.0;
    } else {
        unit = "b";
        dbl = count / 1000000000.0;
    }
    return format.format(dbl) + unit;
}
Example 70
Project: sciencetoolkit-master  File: DeviceSensorConfigViewCreator.java View source code
public static void createView(ModelFragment fragment, View container, SensorWrapper sensor) {
    if (sensor != null) {
        int minDelay = sensor.getMinDelay();
        if (minDelay > 0) {
            DecimalFormat df = new DecimalFormat("#,###");
            String fastestDelayOption = df.format(minDelay) + " µs";
            int validOptionCount = ModelOperations.getValidDeviceSensorDelayOptions(sensor);
            List<String> values = new ArrayList<String>();
            for (int i = 0; i < validOptionCount; i++) {
                values.add(delayLabels[i]);
            }
            values.add(fastestDelayOption);
            fragment.addOptionSelect("delay", "Sensor delay", "The delay between sensor updates.\nNote that lower values increase battery drain.", values, SenseItModelDefaults.SENSOR_DELAY);
        } else {
            SensorConfigViewCreator.addEmptyWarning(fragment);
        }
    }
}
Example 71
Project: spc-master  File: Position.java View source code
/**
    * @see com.sijobe.spc.wrapper.CommandBase#execute(com.sijobe.spc.wrapper.CommandSender, java.util.List)
    */
@Override
public void execute(CommandSender sender, List<?> params) throws CommandException {
    Player player = super.getSenderAsPlayer(sender);
    DecimalFormat f = new DecimalFormat("#.##");
    sender.sendMessageToPlayer("Player position: " + FontColour.AQUA + f.format(player.getPosition().getX()) + FontColour.WHITE + ", " + FontColour.GREEN + f.format(player.getPosition().getY()) + FontColour.WHITE + ", " + FontColour.AQUA + f.format(player.getPosition().getZ()));
}
Example 72
Project: stripe-android-master  File: StoreUtils.java View source code
static String getPriceString(long price, @Nullable Currency currency) {
    Currency displayCurrency = currency == null ? Currency.getInstance("USD") : currency;
    int fractionDigits = displayCurrency.getDefaultFractionDigits();
    int totalLength = String.valueOf(price).length();
    StringBuilder builder = new StringBuilder();
    builder.append('¤');
    if (fractionDigits == 0) {
        for (int i = 0; i < totalLength; i++) {
            builder.append('#');
        }
        DecimalFormat noDecimalCurrencyFormat = new DecimalFormat(builder.toString());
        noDecimalCurrencyFormat.setCurrency(displayCurrency);
        return noDecimalCurrencyFormat.format(price);
    }
    int beforeDecimal = totalLength - fractionDigits;
    for (int i = 0; i < beforeDecimal; i++) {
        builder.append('#');
    }
    // So we display "$0.55" instead of "$.55"
    if (totalLength <= fractionDigits) {
        builder.append('0');
    }
    builder.append('.');
    for (int i = 0; i < fractionDigits; i++) {
        builder.append('0');
    }
    double modBreak = Math.pow(10, fractionDigits);
    double decimalPrice = price / modBreak;
    DecimalFormat decimalFormat = new DecimalFormat(builder.toString());
    decimalFormat.setCurrency(displayCurrency);
    return decimalFormat.format(decimalPrice);
}
Example 73
Project: terasoluna-batch-master  File: MemoryInfo.java View source code
/**
     * Java 仮想マシン�メモリ�容��使用�� 使用を試�る最大メモリ容��情報を返���。
     * @return Java 仮想マシン�メモリ情報
     */
public static String getMemoryInfo() {
    DecimalFormat f1 = new DecimalFormat("#,###KB");
    DecimalFormat f2 = new DecimalFormat("##.#");
    Runtime rt = Runtime.getRuntime();
    long free = rt.freeMemory() / 1024;
    long total = rt.totalMemory() / 1024;
    long max = rt.maxMemory() / 1024;
    long used = total - free;
    double ratio = (used * 100 / (double) total);
    StringBuilder sb = new StringBuilder();
    sb.append("Java memory info : ");
    sb.append("used=");
    sb.append(f1.format(used));
    sb.append(" (");
    sb.append(f2.format(ratio));
    sb.append("%), ");
    sb.append("total=");
    sb.append(f1.format(total));
    sb.append(", ");
    sb.append("max=");
    sb.append(f1.format(max));
    return sb.toString();
}
Example 74
Project: toobs-master  File: PriceFormatHelper.java View source code
/** DOCUMENT ME! */
//private static Log log = LogFactory.getLog(PriceFormatHelper.class);
/**
   * Gets a string that represents the input Price formatted into the proper fromate, and converted
   * into the proper timezone.
   *
   * @return Price-only string formatted with given time zone.
   *
   * @exception XMLTransfromerException if parsing problem occurs
   */
public static String getFormattedPrice(String inputPrice, String priceFormat, String language) throws XMLTransformerException {
    if ((inputPrice == null) || (inputPrice.trim().length() == 0)) {
        inputPrice = "0";
    }
    Locale locale = new Locale(language.substring(2, 4).toLowerCase(), language.substring(0, 2));
    DecimalFormat priceFormatter = (DecimalFormat) NumberFormat.getNumberInstance(locale);
    priceFormatter.setGroupingUsed(true);
    priceFormatter.setMaximumFractionDigits(2);
    priceFormatter.setMinimumFractionDigits(2);
    priceFormatter.applyPattern(priceFormat);
    return priceFormatter.format(new Double(inputPrice));
}
Example 75
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 76
Project: wikiprep-esa-master  File: TestWordsim353.java View source code
/**
	 * @param args
	 * @throws IOException 
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 */
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
    ESASearcher searcher = new ESASearcher();
    String line;
    double val;
    DecimalFormat df = new DecimalFormat("#.##########");
    // read Wordsim-353 human judgements
    InputStream is = IndexModifier.class.getResourceAsStream("/config/wordsim353-combined.tab");
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    //skip first line
    br.readLine();
    System.out.println("Word 1\tWord 2\tHuman (mean)\tScore");
    while ((line = br.readLine()) != null) {
        final String[] parts = line.split("\t");
        if (parts.length != 3)
            break;
        val = searcher.getRelatedness(parts[0], parts[1]);
        if (val == -1) {
            System.out.println(line + "\t0");
        } else {
            System.out.println(line + "\t" + df.format(val));
        }
    }
    br.close();
}
Example 77
Project: xmax-master  File: ScaleModeAuto.java View source code
public void init(List<PlotData> graphs, List<ChannelView> allViews, TimeInterval timeRange, IMeanState meanState, int height) {
    maxValue = Double.NEGATIVE_INFINITY;
    double minValue = Double.POSITIVE_INFINITY;
    DecimalFormat df = new DecimalFormat("#.#####E0");
    for (PlotData data : graphs) {
        double dataMaxValue = meanState.getValue(data.getMaxValue(), data.getMeanValue());
        if (dataMaxValue > maxValue) {
            maxValue = Double.valueOf(df.format(dataMaxValue));
        }
        double dataMinValue = meanState.getValue(data.getMinValue(), data.getMeanValue());
        if (dataMinValue < minValue) {
            minValue = Double.valueOf(df.format(dataMinValue));
            ;
        }
    }
    if (maxValue == minValue) {
        amp = 100.0;
    } else {
        amp = maxValue - minValue;
    }
    this.height = height;
}
Example 78
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 79
Project: GanHuoIO-master  File: SettingCenter.java View source code
public static String formatFileSize(long fileS) {
    java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
    String fileSizeString = "";
    if (fileS < 1024) {
        fileSizeString = df.format((double) fileS) + "B";
    } else if (fileS < 1048576) {
        fileSizeString = df.format((double) fileS / 1024) + "KB";
    } else if (fileS < 1073741824) {
        fileSizeString = df.format((double) fileS / 1048576) + "MB";
    } else {
        fileSizeString = df.format((double) fileS / 1073741824) + "G";
    }
    if (fileSizeString.startsWith(".")) {
        return "0B";
    }
    return fileSizeString;
}
Example 80
Project: spring-framework-master  File: CurrencyStyleFormatter.java View source code
@Override
protected NumberFormat getNumberFormat(Locale locale) {
    DecimalFormat format = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
    format.setParseBigDecimal(true);
    format.setMaximumFractionDigits(this.fractionDigits);
    format.setMinimumFractionDigits(this.fractionDigits);
    if (this.roundingMode != null) {
        format.setRoundingMode(this.roundingMode);
    }
    if (this.currency != null) {
        format.setCurrency(this.currency);
    }
    if (this.pattern != null) {
        format.applyPattern(this.pattern);
    }
    return format;
}
Example 81
Project: SprintNBA-master  File: CacheUtils.java View source code
/**
     * 转�文件大�
     *
     * @return B/KB/MB/GB
     */
public static String formatFileSize(long fileS) {
    java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
    String fileSizeString;
    if (fileS < 1024) {
        fileSizeString = df.format((double) fileS) + "B";
    } else if (fileS < 1048576) {
        fileSizeString = df.format((double) fileS / 1024) + "KB";
    } else if (fileS < 1073741824) {
        fileSizeString = df.format((double) fileS / 1048576) + "MB";
    } else {
        fileSizeString = df.format((double) fileS / 1073741824) + "G";
    }
    return fileSizeString;
}
Example 82
Project: VarexJ-master  File: DecimalFormatTest.java View source code
@Test
public void testDoubleConversion() {
    if (verifyNoPropertyViolation()) {
        StringBuffer sb = new StringBuffer();
        DecimalFormat dFormat = new DecimalFormat();
        sb = dFormat.format(new Double(42), sb, new FieldPosition(0));
        String output = sb.toString();
        try {
            double d = Double.parseDouble(output);
            assert (d == 42.0) : "parsed value differs: " + output;
        } catch (NumberFormatException e) {
            assert false : "output did not parse " + e;
        }
    }
}
Example 83
Project: xalan-j-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
            if (ss.getDecimalFormatCount() > 0)
                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();
                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 84
Project: platform2-master  File: GiroFile.java View source code
public void writeFile(IWContext modinfo, Payment[] ePayments, int bankoffice, int finalpayday, String giroB1, String giroB2, String giroB3, String giroB4, int union_id) throws SQLException, IOException, FinderException {
    Union U = ((UnionHome) IDOLookup.getHomeLegacy(Union.class)).findByPrimaryKey(union_id);
    IWTimestamp datenow = new IWTimestamp();
    String sLowerCaseUnionAbbreviation = U.getAbbrevation().toLowerCase();
    String fileSeperator = System.getProperty("file.separator");
    String filepath = modinfo.getServletContext().getRealPath(fileSeperator + sLowerCaseUnionAbbreviation + fileSeperator);
    StringBuffer fileName = new StringBuffer(sLowerCaseUnionAbbreviation);
    fileName.append(datenow.getDay());
    fileName.append(datenow.getMonth());
    fileName.append(datenow.getMinute());
    fileName.append(".krafa.banki");
    String sWholeFileString = fileSeperator + fileName.toString();
    this.setFileLinkString(fileSeperator + sLowerCaseUnionAbbreviation + sWholeFileString);
    File outputFile = new File(filepath + sWholeFileString);
    FileWriter out = new FileWriter(outputFile);
    char[] c;
    String giroID = "1";
    java.text.DecimalFormat myFormatter = new DecimalFormat("00000000000");
    java.text.DecimalFormat referenceFormatter = new DecimalFormat("00000000");
    java.text.DecimalFormat countFormatter = new DecimalFormat("0000000");
    java.text.DecimalFormat dateFormatter = new DecimalFormat("00");
    StringBuffer SB = new StringBuffer();
    int TotalPrice = 0;
    int price = 0;
    int totalcount = 0;
    //Formfærsla kröfuhafa
    //Bankanúmer þjónustuútibús
    SB.append(bankoffice);
    //inniheldur KR
    SB.append("KR");
    SB.append("      ");
    SB.append("//");
    SB.append("Innheimtukerfi            ");
    SB.append("\n");
    if (!giroB1.equals("")) {
        SB.append("B1080");
        // Kennitala kröfuhafa
        SB.append("          ");
        // Autt
        SB.append("          ");
        // Autt
        SB.append(giroB1);
        SB.append("\n");
    }
    if (!giroB2.equals("")) {
        SB.append("B2080");
        // Kennitala kröfuhafa
        SB.append("          ");
        // Autt
        SB.append("          ");
        // Autt
        SB.append(giroB2);
        SB.append("\n");
    }
    if (!giroB3.equals("")) {
        SB.append("B3080");
        // Kennitala kröfuhafa
        SB.append("          ");
        // Autt
        SB.append("          ");
        // Autt
        SB.append(giroB3);
        SB.append("\n");
    }
    if (!giroB4.equals("")) {
        SB.append("B4080");
        // Kennitala kröfuhafa
        SB.append("          ");
        // Autt
        SB.append("          ");
        // Autt
        SB.append(giroB4);
        SB.append("\n");
    }
    // write the first part to file
    c = SB.toString().toCharArray();
    out.write(c);
    Member M;
    IWTimestamp PayDate;
    String year, month, day, kt;
    int theMonth;
    String strFinalDay = dateFormatter.format(finalpayday);
    for (int i = 0; i < ePayments.length; i++) {
        SB = new StringBuffer();
        M = ((MemberHome) IDOLookup.getHomeLegacy(Member.class)).findByPrimaryKey(ePayments[i].getMemberId());
        kt = M.getSocialSecurityNumber();
        PayDate = new IWTimestamp(ePayments[i].getPaymentDate());
        price = ePayments[i].getPrice();
        year = String.valueOf(PayDate.getYear());
        month = dateFormatter.format(PayDate.getMonth());
        day = dateFormatter.format(PayDate.getDay());
        // Inniheldur C2 og 080
        SB.append("C2080");
        // kennitala kröfuhafa(10)
        SB.append("          ");
        //kennitala greiðanda(10)
        SB.append(kt);
        //Efnislykill (5)
        SB.append("EEEEE");
        TotalPrice += price;
        //kröfuupphæð sem gildir að gjalddaga(11)
        SB.append(myFormatter.format(price));
        // "aurar" (,2)
        SB.append("00");
        // kröfuupphæð sem gildir frá og með gjalddaga eða núll(11,2)
        SB.append("             ");
        // tilvísun (16)(8+8):
        SB.append(referenceFormatter.format(M.getID()));
        SB.append(referenceFormatter.format(ePayments[i].getID()));
        //autt svæði (1)
        SB.append(" ");
        // Gjalddagi seðils eyða ef reglulegar kröfur (6)
        SB.append(year);
        SB.append(month);
        SB.append(day);
        // Eindagi seðils eyða ef reglulegar kröfur eða aldrei vanskil(6)
        if (finalpayday != 0) {
            SB.append(year);
            SB.append(month);
            SB.append(strFinalDay);
        } else {
            SB.append("      ");
        }
        // Seðilnúmer (7)
        SB.append("       ");
        // Vanskilakostnaður (11)
        SB.append("           ");
        SB.append("S");
        SB.append("\n");
        totalcount++;
        // write a line to file
        c = SB.toString().toCharArray();
        out.write(c);
    }
    SB = new StringBuffer();
    // á að innihalda "LF" (2)
    SB.append("LF");
    // // 080 (3)
    SB.append("080");
    // Kt.kröfuhafa (10)
    SB.append("          ");
    // autt (10)
    SB.append("          ");
    SB.append(myFormatter.format(TotalPrice));
    // "aurar" (,2)
    SB.append("00");
    //Upphæð 2
    SB.append("             ");
    SB.append(countFormatter.format(totalcount));
    SB.append("\n");
    // write the last part to file
    c = SB.toString().toCharArray();
    out.write(c);
    out.close();
//add(SB.toString());
}
Example 85
Project: com.mzeat-master  File: StringUtils.java View source code
public static String formatDistance(String distance) {
    int length = distance.length();
    if (length <= 3) {
        distance = distance + "ç±³";
    } else {
        double dis = Double.valueOf(distance);
        dis = dis / 1000;
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
        distance = String.valueOf(df.format(dis)) + "公里";
    }
    return distance;
}
Example 86
Project: pentaho-reporting-master  File: ConvertToNumberExpression.java View source code
/**
   * Parses the value read from the column specified by the given field-name and tries to parse it into a Number using
   * the given DecimalFormat-pattern.
   *
   * @return the value of the function.
   */
public Object getValue() {
    final DataRow dataRow = getDataRow();
    // get the row directly as a Number
    final Object o = dataRow.get(field);
    // check if that thing is a Number
    if (o instanceof Number) {
        return o;
    }
    // get a string and convert
    final String formatString = getFormat();
    try {
        Locale localeUsed = locale;
        if (localeUsed == null) {
            localeUsed = getResourceBundleFactory().getLocale();
        }
        if (decimalFormat == null || ObjectUtilities.equal(lastLocale, localeUsed) == false) {
            final String effectiveFormatString;
            if (formatString == null || formatString.length() == 0) {
                // this is a workaround for a bug in JDK 1.5
                effectiveFormatString = ConvertToNumberExpression.DECIMALFORMAT_DEFAULT_PATTERN;
            } else {
                effectiveFormatString = formatString;
            }
            lastLocale = localeUsed;
            decimalFormat = new DecimalFormat(effectiveFormatString);
            decimalFormat.setParseBigDecimal(true);
            decimalFormat.setDecimalFormatSymbols(new DecimalFormatSymbols(localeUsed));
        }
        return decimalFormat.parse(String.valueOf(o));
    } catch (ParseException e) {
        return ConvertToNumberExpression.ZERO;
    }
}
Example 87
Project: GeDBIT-master  File: Pair.java View source code
public String toString() {
    java.text.DecimalFormat format = new java.text.DecimalFormat("#.######");
    format.setMaximumFractionDigits(6);
    String firstString = (first instanceof Double) ? format.format(((Double) first).doubleValue()) : first.toString();
    String secondString = (second instanceof Double) ? format.format(((Double) second).doubleValue()) : second.toString();
    return "(" + firstString + ", " + secondString + ")";
}
Example 88
Project: MinorThird-master  File: CrossValidatedDataset.java View source code
private String classDistributionString(ExampleSchema schema, DatasetIndex index) {
    StringBuffer buf = new StringBuffer("");
    java.text.DecimalFormat fmt = new java.text.DecimalFormat("#####");
    for (int i = 0; i < schema.getNumberOfClasses(); i++) {
        if (buf.length() > 0)
            buf.append("; ");
        String label = schema.getClassName(i);
        buf.append(fmt.format(index.size(label)) + " " + label);
    }
    return buf.toString();
}
Example 89
Project: open-mika-master  File: DecimalFormatTest.java View source code
/*
    @TestTargetNew(
        level = TestLevel.PARTIAL,
        notes = "Regression test for AttributedCharacterIterator.",
        method = "formatToCharacterIterator",
        args = {java.lang.Object.class}
    )
    public void testAttributedCharacterIterator() throws Exception {
        // Regression for http://issues.apache.org/jira/browse/HARMONY-333
        AttributedCharacterIterator iterator = new DecimalFormat()
                .formatToCharacterIterator(new Integer(1));
        assertNotNull(iterator);
        assertFalse("attributes should exist", iterator.getAttributes()
                .isEmpty());
    }

    /*
    @TestTargetNew(
        level = TestLevel.PARTIAL_COMPLETE,
        notes = "",
        method = "formatToCharacterIterator",
        args = {java.lang.Object.class}
    )
    @KnownFailure("formatting numbers with more than ~300 digits doesn't work."
            + " Also the third test doesn't round the string like the RI does")
    */
public void test_formatToCharacterIterator() throws Exception {
    AttributedCharacterIterator iterator;
    int[] runStarts;
    int[] runLimits;
    String result;
    char current;
    iterator = new DecimalFormat().formatToCharacterIterator(new BigDecimal("1.23456789E1234"));
    runStarts = new int[] { 0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14 };
    runLimits = new int[] { 2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15 };
    // 000,000,000,000....
    result = "12,345,678,900,";
    current = iterator.current();
    for (int i = 0; i < runStarts.length; i++) {
        assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
        assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
        assertEquals("wrong char @" + i, result.charAt(i), current);
        current = iterator.next();
    }
    assertEquals(0, iterator.getBeginIndex());
    assertEquals(1646, iterator.getEndIndex());
    iterator = new DecimalFormat().formatToCharacterIterator(new BigDecimal("1.23456789E301"));
    runStarts = new int[] { 0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14 };
    runLimits = new int[] { 2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15 };
    // 000,000,000,000....
    result = "12,345,678,900,";
    current = iterator.current();
    for (int i = 0; i < runStarts.length; i++) {
        assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
        assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
        assertEquals("wrong char @" + i, result.charAt(i), current);
        current = iterator.next();
    }
    assertEquals(0, iterator.getBeginIndex());
    assertEquals(402, iterator.getEndIndex());
    iterator = new DecimalFormat().formatToCharacterIterator(new BigDecimal("1.2345678E4"));
    runStarts = new int[] { 0, 0, 2, 3, 3, 3, 6, 7, 7, 7 };
    runLimits = new int[] { 2, 2, 3, 6, 6, 6, 7, 10, 10, 10 };
    result = "12,345.678";
    current = iterator.current();
    for (int i = 0; i < runStarts.length; i++) {
        assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
        assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
        assertEquals("wrong char @" + i, result.charAt(i), current);
        current = iterator.next();
    }
    assertEquals(0, iterator.getBeginIndex());
    assertEquals(10, iterator.getEndIndex());
    iterator = new DecimalFormat().formatToCharacterIterator(new BigInteger("123456789"));
    runStarts = new int[] { 0, 0, 0, 3, 4, 4, 4, 7, 8, 8, 8 };
    runLimits = new int[] { 3, 3, 3, 4, 7, 7, 7, 8, 11, 11, 11 };
    result = "123,456,789";
    current = iterator.current();
    for (int i = 0; i < runStarts.length; i++) {
        assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart());
        assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit());
        assertEquals("wrong char @" + i, result.charAt(i), current);
        current = iterator.next();
    }
    assertEquals(0, iterator.getBeginIndex());
    assertEquals(11, iterator.getEndIndex());
}
Example 90
Project: resin-master  File: FormatNumberFun.java View source code
/**
   * Evaluate the function.
   *
   * @param pattern The context pattern.
   * @param args The evaluated arguments
   */
public Object eval(Node node, ExprEnvironment env, AbstractPattern pattern, ArrayList args) throws XPathException {
    if (args.size() < 2)
        return null;
    double number = Expr.toDouble(args.get(0));
    String format = Expr.toString(args.get(1));
    String localeName = null;
    if (args.size() > 2)
        localeName = Expr.toString(args.get(2));
    else
        localeName = "*";
    if (format == null)
        return null;
    DecimalFormatSymbols symbols;
    symbols = (DecimalFormatSymbols) locales.get(localeName);
    try {
        DecimalFormat form;
        if (symbols == null)
            form = new DecimalFormat(format);
        else {
            form = new DecimalFormat(format, symbols);
        }
        return form.format(number);
    } catch (Exception e) {
        throw new XPathException(e);
    }
}
Example 91
Project: Tundra.java-master  File: BigDecimalHelper.java View source code
/**
     * Parses the given string and returns a decimal representation.
     *
     * @param decimalString  A string to be parsed as a decimal.
     * @param decimalPattern A java.text.DecimalFormat pattern string describing the format of the given decimal
     *                       string.
     * @param locale         The locale to use if the string is only parseable in this localized format.
     * @return               A decimal representation of the given string.
     */
public static BigDecimal parse(String decimalString, String decimalPattern, Locale locale) {
    if (decimalString == null)
        return null;
    BigDecimal result;
    if (decimalPattern == null) {
        try {
            result = new BigDecimal(decimalString);
        } catch (NumberFormatException ex) {
            try {
                result = new BigDecimal(NumberFormat.getInstance(LocaleHelper.normalize(locale)).parse(decimalString).doubleValue());
            } catch (ParseException pe) {
                throw new IllegalArgumentException(pe);
            }
        }
    } else {
        DecimalFormat parser = new DecimalFormat(decimalPattern);
        parser.setParseBigDecimal(true);
        try {
            result = (BigDecimal) parser.parse(decimalString);
        } catch (ParseException ex) {
            throw new IllegalArgumentException("Unparseable decimal: '" + decimalString + "' does not conform to pattern '" + decimalPattern + "'", ex);
        }
    }
    return result;
}
Example 92
Project: 4dbb-master  File: DoubleSpinner.java View source code
private void initialize(JSpinner spinner, DecimalFormat format) {
    SpinnerModel model = spinner.getModel();
    NumberFormatter formatter = new NumberFormatter(format);
    DefaultFormatterFactory factory = new DefaultFormatterFactory(formatter);
    JFormattedTextField ftf = getTextField();
    ftf.setEditable(true);
    ftf.setFormatterFactory(factory);
    ftf.setHorizontalAlignment(SwingConstants.RIGHT);
    /* TBD - initializing the column width of the text field
			 * is imprecise and doing it here is tricky because 
			 * the developer may configure the formatter later.
			 */
    try {
        String valString = formatter.valueToString(model.getNextValue());
        ftf.setColumns(valString.length());
    } catch (ParseException e) {
    }
}
Example 93
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 94
Project: akvo-flow-mobile-master  File: GeoUtil.java View source code
public static String getDisplayLength(double distance) {
    // default: km
    DecimalFormat df = new DecimalFormat("###,###.##");
    String unit = "km";
    // convert from meters to km
    Double factor = 0.001;
    // for distances smaller than 1 km, use meters as unit
    if (distance < 1000.0) {
        factor = 1.0;
        unit = "m";
    //df = new DecimalFormat("#"); // only whole meters
    }
    double dist = distance * factor;
    return df.format(dist) + " " + unit;
}
Example 95
Project: alfresco-android-app-master  File: NumberField.java View source code
// ///////////////////////////////////////////////////////////////////////////
// READ
// ///////////////////////////////////////////////////////////////////////////
public String getHumanReadableReadValue() {
    if (originalValue == null) {
        return getString(R.string.form_message_empty);
    }
    if (originalValue == null) {
        return getString(R.string.form_message_empty);
    }
    if (editionValue instanceof Double) {
        DecimalFormat df = new DecimalFormat("0.#");
        return df.format((Double) editionValue);
    }
    return originalValue.toString();
}
Example 96
Project: Android-Kontakt-Beacons-master  File: BeaconCollectionAdapter.java View source code
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    if (v == null) {
        v = inflater.inflate(R.layout.list_item, null);
    }
    Beacon beacon = getItem(position);
    TextView mac = (TextView) v.findViewById(R.id.macAddress);
    TextView uuid = (TextView) v.findViewById(R.id.uuidNumber);
    TextView major = (TextView) v.findViewById(R.id.majorNumber);
    TextView minor = (TextView) v.findViewById(R.id.minorNumber);
    TextView distance = (TextView) v.findViewById(R.id.distance);
    mac.setText(beacon.getBluetoothAddress());
    uuid.setText(beacon.getId1().toString());
    major.setText(beacon.getId2().toString());
    minor.setText(beacon.getId3().toString());
    distance.setText(new DecimalFormat("#0.000").format(beacon.getDistance()));
    return v;
}
Example 97
Project: android-lite-orm-master  File: TestGetClass.java View source code
public static void main(String[] args) {
    System.out.println(new DecimalFormat("#.00").format(4563.125434));
    try {
        Field fb = A.class.getDeclaredField("b");
        System.out.println(fb.getType());
        System.out.println(fb.getType().getComponentType());
        System.out.println(Collection.class.isAssignableFrom(fb.getType()));
        Field fl = A.class.getDeclaredField("l");
        System.out.println(fl.getType());
        System.out.println(Collection.class.isAssignableFrom(fl.getType()));
        System.out.println(fl.getType().getComponentType());
        System.out.println(getGenericType(fl));
        System.out.println(getGenericType(fl).getComponentType());
        Field fa = A.class.getDeclaredField("a");
        System.out.println(fa.getType());
        System.out.println(fa.getType().getComponentType());
        System.out.println(Collection.class.isAssignableFrom(fa.getType()));
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
}
Example 98
Project: android-sdk-sources-for-api-level-23-master  File: BlasControls.java View source code
private void writeResults() {
    // write result into a file
    File externalStorage = Environment.getExternalStorageDirectory();
    if (!externalStorage.canWrite()) {
        Log.v(TAG, "sdcard is not writable");
        return;
    }
    File resultFile = new File(externalStorage, RESULT_FILE);
    resultFile.setWritable(true, false);
    try {
        BufferedWriter rsWriter = new BufferedWriter(new FileWriter(resultFile));
        Log.v(TAG, "Saved results in: " + resultFile.getAbsolutePath());
        java.text.DecimalFormat df = new java.text.DecimalFormat("######.####");
        for (int ct = 0; ct < BlasTestList.TestName.values().length; ct++) {
            String t = BlasTestList.TestName.values()[ct].toString();
            final float r = mResults[ct];
            String s = new String("" + t + ", " + df.format(r));
            rsWriter.write(s + "\n");
        }
        rsWriter.close();
    } catch (IOException e) {
        Log.v(TAG, "Unable to write result file " + e.getMessage());
    }
}
Example 99
Project: Android-Talk-Demos-master  File: EnglishNumberToWords.java View source code
public static String convert(long number) {
    // 0 to 999 999 999 999
    if (number == 0) {
        return "zero";
    }
    String snumber = Long.toString(number);
    // pad with "0"
    String mask = "000000000000";
    DecimalFormat df = new DecimalFormat(mask);
    snumber = df.format(number);
    // XXXnnnnnnnnn
    int billions = Integer.parseInt(snumber.substring(0, 3));
    // nnnXXXnnnnnn
    int millions = Integer.parseInt(snumber.substring(3, 6));
    // nnnnnnXXXnnn
    int hundredThousands = Integer.parseInt(snumber.substring(6, 9));
    // nnnnnnnnnXXX
    int thousands = Integer.parseInt(snumber.substring(9, 12));
    String tradBillions;
    switch(billions) {
        case 0:
            tradBillions = "";
            break;
        case 1:
            tradBillions = convertLessThanOneThousand(billions) + " billion ";
            break;
        default:
            tradBillions = convertLessThanOneThousand(billions) + " billion ";
    }
    String result = tradBillions;
    String tradMillions;
    switch(millions) {
        case 0:
            tradMillions = "";
            break;
        case 1:
            tradMillions = convertLessThanOneThousand(millions) + " million ";
            break;
        default:
            tradMillions = convertLessThanOneThousand(millions) + " million ";
    }
    result = result + tradMillions;
    String tradHundredThousands;
    switch(hundredThousands) {
        case 0:
            tradHundredThousands = "";
            break;
        case 1:
            tradHundredThousands = "one thousand ";
            break;
        default:
            tradHundredThousands = convertLessThanOneThousand(hundredThousands) + " thousand ";
    }
    result = result + tradHundredThousands;
    String tradThousand;
    tradThousand = convertLessThanOneThousand(thousands);
    result = result + tradThousand;
    // remove extra spaces!
    return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
}
Example 100
Project: AndroidExercise-master  File: TestGetClass.java View source code
public static void main(String[] args) {
    System.out.println(new DecimalFormat("#.00").format(4563.125434));
    try {
        Field fb = A.class.getDeclaredField("b");
        System.out.println(fb.getType());
        System.out.println(fb.getType().getComponentType());
        System.out.println(Collection.class.isAssignableFrom(fb.getType()));
        Field fl = A.class.getDeclaredField("l");
        System.out.println(fl.getType());
        System.out.println(Collection.class.isAssignableFrom(fl.getType()));
        System.out.println(fl.getType().getComponentType());
        System.out.println(getGenericType(fl));
        System.out.println(getGenericType(fl).getComponentType());
        Field fa = A.class.getDeclaredField("a");
        System.out.println(fa.getType());
        System.out.println(fa.getType().getComponentType());
        System.out.println(Collection.class.isAssignableFrom(fa.getType()));
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
}
Example 101
Project: AndroidWallet-master  File: BalancesListAdapter.java View source code
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    double balance;
    DecimalFormat formatter = new DecimalFormat("#,###.######");
    if (convertView == null) {
        convertView = l_Inflater.inflate(R.layout.balance_item, null);
        holder = new ViewHolder();
        holder.currency = (TextView) convertView.findViewById(R.id.currency);
        holder.currencyName = (TextView) convertView.findViewById(R.id.currencyName);
        holder.balance = (TextView) convertView.findViewById(R.id.balance);
        //holder.image 		= (ImageView) convertView.findViewById(R.id.currencyImage);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    balance = balancesList.get(position).getBalance();
    holder.currency.setText(balancesList.get(position).getCurrency());
    holder.currencyName.setText(balancesList.get(position).getCurrencyName());
    holder.balance.setText(balance != 0 ? formatter.format(balance) : "0");
    return convertView;
}