Java 类java.text.DecimalFormatSymbols 实例源码

项目:java-tools    文件:CoreTypes.java   
public static String castToString(double d)
{
    double dAbs = Math.abs(d);
    DecimalFormatSymbols decfmtsymb = new DecimalFormatSymbols(java.util.Locale.US);    // US locale represents numbers with a . as comma and without any (ten)thousend separators.
    decfmtsymb.setInfinity("INF");
    decfmtsymb.setNaN("NaN");
    DecimalFormat decfmt = new DecimalFormat((dAbs > 1E7 || dAbs < 1E-3) && dAbs > 0.0 ?
            "0.##############E000" : "0.#############", decfmtsymb);

    String s = decfmt.format(d);
    // 1.234E567 => 1.234E+567
    int e = s.indexOf("E");
    if (e > 0 && s.charAt(e+1) != '-' )
    s = s.substring(0, e) + "E+" + s.substring(e+1);
    return s;
}
项目:openjdk-jdk10    文件:DFSSerialization.java   
private DecimalFormatSymbols readTestObject(File inputFile){
    try (InputStream istream = inputFile.getName().endsWith(".txt") ?
                                   HexDumpReader.getStreamFromHexDump(inputFile) :
                                   new FileInputStream(inputFile)) {
        ObjectInputStream p = new ObjectInputStream(istream);
        DecimalFormatSymbols dfs = (DecimalFormatSymbols)p.readObject();
        return dfs;
    } catch (Exception e) {
        errln("Test Malfunction in DFSSerialization: Exception while reading the object");
        /*
         * logically should not throw this exception as errln throws exception
         * if not thrown yet - but in case errln got changed
         */
        throw new RuntimeException("Test Malfunction: re-throwing the exception", e);
    }
}
项目:openjdk-jdk10    文件:TestShrinkAuxiliaryData.java   
private void printTestInfo(int maxCacheSize) {

        DecimalFormat grouped = new DecimalFormat("000,000");
        DecimalFormatSymbols formatSymbols = grouped.getDecimalFormatSymbols();
        formatSymbols.setGroupingSeparator(' ');
        grouped.setDecimalFormatSymbols(formatSymbols);

        System.out.format(
                "Test will use %s bytes of memory of %s available%n"
                + "Available memory is %s with %d bytes pointer size - can save %s pointers%n"
                + "Max cache size: 2^%d = %s elements%n",
                grouped.format(ShrinkAuxiliaryDataTest.getMemoryUsedByTest()),
                grouped.format(Runtime.getRuntime().maxMemory()),
                grouped.format(Runtime.getRuntime().maxMemory()
                        - ShrinkAuxiliaryDataTest.getMemoryUsedByTest()),
                Unsafe.ADDRESS_SIZE,
                grouped.format((Runtime.getRuntime().freeMemory()
                        - ShrinkAuxiliaryDataTest.getMemoryUsedByTest())
                        / Unsafe.ADDRESS_SIZE),
                maxCacheSize,
                grouped.format((int) Math.pow(2, maxCacheSize))
        );
    }
项目:jreliability    文件:MeasuresPanel.java   
/**
 * Initializes the panel.
 */
private void initialize() {
    this.setLayout(new GridLayout(0, 1, 10, 10));

    DecimalFormatSymbols symbol = new DecimalFormatSymbols();

    symbol.setDecimalSeparator('.');
    DecimalFormat decimalFormat = new DecimalFormat();
    decimalFormat.setDecimalFormatSymbols(symbol);
    mtFieldFormat = decimalFormat;

    Double expected = firstMoment.evaluate(reliabilityFunction);

    JLabel expectedLabel = new JLabel("Expected Value:");
    JPanel propertiesPanel = createPropertiesPanel(expected, expectedLabel);
    JPanel mttfPanel = createMttfPanel(expected, expectedLabel.getPreferredSize());
    JPanel mtPanel = createMtPanel(expectedLabel.getPreferredSize());

    this.add(propertiesPanel);
    this.add(mttfPanel);
    this.add(mtPanel);

    revalidate();
    repaint();
}
项目:OpenJSharp    文件:NumberFormatProviderImpl.java   
private NumberFormat getInstance(Locale locale,
                                        int choice) {
    if (locale == null) {
        throw new NullPointerException();
    }

    LocaleProviderAdapter adapter = LocaleProviderAdapter.forType(type);
    String[] numberPatterns = adapter.getLocaleResources(locale).getNumberPatterns();
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
    int entry = (choice == INTEGERSTYLE) ? NUMBERSTYLE : choice;
    DecimalFormat format = new DecimalFormat(numberPatterns[entry], symbols);

    if (choice == INTEGERSTYLE) {
        format.setMaximumFractionDigits(0);
        format.setDecimalSeparatorAlwaysShown(false);
        format.setParseIntegerOnly(true);
    } else if (choice == CURRENCYSTYLE) {
        adjustForCurrencyDefaultFractionDigits(format, symbols);
    }

    return format;
}
项目:bean-grid    文件:AbstractStringToNumberConverterBean.java   
/**
 * Returns the format used by
 * {@link #convertToPresentation(Object, ValueContext)} and
 * {@link #convertToModel(Object, ValueContext)}.
 *
 * @param context
 *            value context to use
 * @return A NumberFormat instance
 */
protected NumberFormat getFormat(ValueContext context) {
    String pattern = null;

    Object data = context.getComponent().map(AbstractComponent.class::cast).map(component -> component.getData())
            .orElse(null);
    if (data instanceof ColumnDefinition) {
        pattern = ((ColumnDefinition) data).getFormat()
                .orElse(configurationProvider.getNumberFormatPattern().orElse(null));
    }

    Locale locale = context.getLocale().orElse(configurationProvider.getLocale());

    if (pattern == null) {
        return NumberFormat.getNumberInstance(locale);
    }

    return new DecimalFormat(pattern, new DecimalFormatSymbols(locale));
}
项目:openjdk-jdk10    文件:NumberFormatProviderImpl.java   
/**
 * Adjusts the minimum and maximum fraction digits to values that
 * are reasonable for the currency's default fraction digits.
 */
private static void adjustForCurrencyDefaultFractionDigits(
        DecimalFormat format, DecimalFormatSymbols symbols) {
    Currency currency = symbols.getCurrency();
    if (currency == null) {
        try {
            currency = Currency.getInstance(symbols.getInternationalCurrencySymbol());
        } catch (IllegalArgumentException e) {
        }
    }
    if (currency != null) {
        int digits = currency.getDefaultFractionDigits();
        if (digits != -1) {
            int oldMinDigits = format.getMinimumFractionDigits();
            // Common patterns are "#.##", "#.00", "#".
            // Try to adjust all of them in a reasonable way.
            if (oldMinDigits == format.getMaximumFractionDigits()) {
                format.setMinimumFractionDigits(digits);
                format.setMaximumFractionDigits(digits);
            } else {
                format.setMinimumFractionDigits(Math.min(digits, oldMinDigits));
                format.setMaximumFractionDigits(digits);
            }
        }
    }
}
项目:LogisticApp    文件:MenuContratacaoTransporteFrame.java   
private void initializeTextFields() {

        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        symbols.setDecimalSeparator('.');

        NumberFormat format = new DecimalFormat("0.00", symbols);
        format.setMaximumFractionDigits(2);

        NumberFormatter formatter = new NumberFormatter(format);
        formatter.setMinimum(0.0);
        formatter.setMaximum(10000000.0);
        formatter.setAllowsInvalid(false);

        this.txtPeso = new JFormattedTextField(formatter);
        this.txtPeso.setValue(0.0);

        GridBagConstraints gbc_textField = new GridBagConstraints();
        gbc_textField.gridwidth = 10;
        gbc_textField.insets = new Insets(0, 0, 5, 0);
        gbc_textField.fill = GridBagConstraints.BOTH;
        gbc_textField.gridx = 2;
        gbc_textField.gridy = 10;
        this.panelSecond.add(this.txtPeso, gbc_textField);
        this.txtPeso.setColumns(10);

    }
项目:java-tools    文件:Duration.java   
public String toYearMonthString()
{
    StringBuffer s = new StringBuffer();
    if (bNegative)
        s.append("-");
    s.append("P");
    if (year != 0) 
    {
        s.append(new DecimalFormat("0", new DecimalFormatSymbols(java.util.Locale.US)).format( (long) java.lang.Math.abs(year) ) );
        s.append("Y");
    }
    if (month != 0) 
    {
        s.append(new DecimalFormat("0", new DecimalFormatSymbols(java.util.Locale.US)).format( (long) java.lang.Math.abs(month) ) );
        s.append("M");
    }
    if (s.length() == 1)
        s.append("0M");
    return s.toString();
}
项目:micrometer    文件:DoubleFormat.java   
@Override
protected NumberFormat initialValue() {

    // Always create the formatter for the US locale in order to avoid this bug:
    // https://github.com/indeedeng/java-dogstatsd-client/issues/3
    final NumberFormat numberFormatter = NumberFormat.getInstance(Locale.US);
    numberFormatter.setGroupingUsed(false);
    numberFormatter.setMaximumFractionDigits(6);

    // we need to specify a value for Double.NaN that is recognized by dogStatsD
    if (numberFormatter instanceof DecimalFormat) { // better safe than a runtime error
        final DecimalFormat decimalFormat = (DecimalFormat) numberFormatter;
        final DecimalFormatSymbols symbols = decimalFormat.getDecimalFormatSymbols();
        symbols.setNaN("NaN");
        decimalFormat.setDecimalFormatSymbols(symbols);
    }

    return numberFormatter;
}
项目:openjdk-jdk10    文件:NumberFormatProviderImpl.java   
private NumberFormat getInstance(Locale locale,
                                        int choice) {
    if (locale == null) {
        throw new NullPointerException();
    }

    LocaleProviderAdapter adapter = LocaleProviderAdapter.forType(type);
    String[] numberPatterns = adapter.getLocaleResources(locale).getNumberPatterns();
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
    int entry = (choice == INTEGERSTYLE) ? NUMBERSTYLE : choice;
    DecimalFormat format = new DecimalFormat(numberPatterns[entry], symbols);

    if (choice == INTEGERSTYLE) {
        format.setMaximumFractionDigits(0);
        format.setDecimalSeparatorAlwaysShown(false);
        format.setParseIntegerOnly(true);
    } else if (choice == CURRENCYSTYLE) {
        adjustForCurrencyDefaultFractionDigits(format, symbols);
    }

    return format;
}
项目:EARLGREY    文件:GeoAlgorithm.java   
public static JSONArray cluster_simplfication(JSONArray coords, double tolerance){
    DecimalFormat df = new DecimalFormat("0.0000");
    DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
    simbolos.setDecimalSeparator('.');
    df.setDecimalFormatSymbols(simbolos);
    double pivotx = coords.getDouble(0);
    double pivoty = coords.getDouble(1);
    JSONArray newcoords = new JSONArray();
    newcoords.put(new Float(df.format(pivotx)));
    newcoords.put(new Float(df.format(pivoty)));
    for(int i=2; i<coords.length(); i++){
        if(Math.sqrt(Math.pow((coords.getDouble(i)-pivotx), 2)+Math.pow((coords.getDouble(i+1)-pivoty), 2)) >= tolerance){
            pivotx = coords.getDouble(i);
            pivoty = coords.getDouble(i+1);
            newcoords.put(new Float(df.format(pivotx)));
            newcoords.put(new Float(df.format(pivoty)));
        }
        i++;
    }
    return newcoords;
}
项目:oscm    文件:DurationValidation.java   
/**
 * Validates that the given value contains only digits, but not e.g. a
 * character 'd'. Java would interpret the input 3d as double value 3.0.
 * Anyway, this must not succeed.
 * 
 * @param valueToCheck
 *            The value to be checked.
 * @param component
 *            The current component.
 * @return <code>true</code> if the value is valid.
 */
private static boolean validateOnlyDigits(String valueToCheck,
        FacesContext facesContext) {
    Locale locale = LocaleHandler.getLocaleFromString(BaseBean
            .getUserFromSession(facesContext).getLocale());
    DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
    boolean decSepFound = false;

    for (char c : valueToCheck.toCharArray()) {
        if (!decSepFound && c == dfs.getDecimalSeparator()) {
            decSepFound = true;
            continue;
        }
        if (c == dfs.getGroupingSeparator()) {
            continue;
        }
        if (!Character.isDigit(c)) {
            return false;
        }
    }

    return true;
}
项目:okwallet    文件:BtcFormat.java   
/** Return a representation of the pattern used by this instance for formatting and
 *  parsing.  The format is similar to, but not the same as the format recognized by the
 *  {@link Builder#pattern} and {@link Builder#localizedPattern} methods.  The pattern
 *  returned by this method is localized, any currency signs expressed are literally, and
 *  optional fractional decimal places are shown grouped in parentheses. */
public String pattern() { synchronized(numberFormat) {
    StringBuilder groups = new StringBuilder();
    for (int group : decimalGroups) {
        groups.append("(").append(Strings.repeat("#", group)).append(")");
    }
    DecimalFormatSymbols s = numberFormat.getDecimalFormatSymbols();
    String digit = String.valueOf(s.getDigit());
    String exp = s.getExponentSeparator();
    String groupSep = String.valueOf(s.getGroupingSeparator());
    String moneySep = String.valueOf(s.getMonetaryDecimalSeparator());
    String zero = String.valueOf(s.getZeroDigit());
    String boundary = String.valueOf(s.getPatternSeparator());
    String minus = String.valueOf(s.getMinusSign());
    String decSep = String.valueOf(s.getDecimalSeparator());

    String prefixAndNumber = "(^|" + boundary+ ")" +
        "([^" + Matcher.quoteReplacement(digit + zero + groupSep + decSep + moneySep) + "']*('[^']*')?)*" +
        "[" + Matcher.quoteReplacement(digit + zero + groupSep + decSep + moneySep + exp) + "]+";

    return numberFormat.toLocalizedPattern().
        replaceAll(prefixAndNumber, "$0" + groups.toString()).
           replaceAll("¤¤", Matcher.quoteReplacement(coinCode())).
           replaceAll("¤", Matcher.quoteReplacement(coinSymbol()));
}}
项目:oscm    文件:PriceConverterTest.java   
@Test
public void testgetValueToDisplay() throws Exception {
    final DecimalFormatSymbols dfs = new DecimalFormatSymbols(
            priceConverter.getActiveLocale());
    StringBuffer strMoneyBuffer = new StringBuffer();
    strMoneyBuffer.append("123");
    strMoneyBuffer.append(dfs.getDecimalSeparator());
    strMoneyBuffer.append("45");

    Assert.assertEquals(
            strMoneyBuffer.toString(),
            priceConverter.getValueToDisplay(
                    new BigDecimal(strMoneyBuffer.toString()), true));

    strMoneyBuffer.delete(0, strMoneyBuffer.length());
    strMoneyBuffer.append("123");
    strMoneyBuffer.append(dfs.getDecimalSeparator());
    strMoneyBuffer.append("00");

    Assert.assertEquals(
            "123.00",
            priceConverter.getValueToDisplay(
                    priceConverter.parse(strMoneyBuffer.toString()), true));

}
项目:de.flapdoodle.solid    文件:NumberFormatFilter.java   
@Override
public Object apply(Object input, Map<String, Object> args, PebbleTemplate self, EvaluationContext context, int lineNumber) throws PebbleException{
    if (input == null) {
        return null;
    }
    if (!(input instanceof Number)) {
        throw new PebbleException(null, "The input for the 'NumberFormat' filter has to be a number.", lineNumber, self.getName());
    }

    Number number = (Number) input;

    Locale locale = context.getLocale();

    if (args.get("format") != null) {
        Format format = new DecimalFormat((String) args.get("format"), new DecimalFormatSymbols(locale));
        return format.format(number);
    } else {
        NumberFormat numberFormat = NumberFormat.getInstance(locale);
        return numberFormat.format(number);
    }
}
项目:creacoinj    文件:BtcFormat.java   
/** Return a representation of the pattern used by this instance for formatting and
 *  parsing.  The format is similar to, but not the same as the format recognized by the
 *  {@link Builder#pattern} and {@link Builder#localizedPattern} methods.  The pattern
 *  returned by this method is localized, any currency signs expressed are literally, and
 *  optional fractional decimal places are shown grouped in parentheses. */
public String pattern() { synchronized(numberFormat) {
    StringBuilder groups = new StringBuilder();
    for (int group : decimalGroups) {
        groups.append("(").append(Strings.repeat("#", group)).append(")");
    }
    DecimalFormatSymbols s = numberFormat.getDecimalFormatSymbols();
    String digit = String.valueOf(s.getDigit());
    String exp = s.getExponentSeparator();
    String groupSep = String.valueOf(s.getGroupingSeparator());
    String moneySep = String.valueOf(s.getMonetaryDecimalSeparator());
    String zero = String.valueOf(s.getZeroDigit());
    String boundary = String.valueOf(s.getPatternSeparator());
    String minus = String.valueOf(s.getMinusSign());
    String decSep = String.valueOf(s.getDecimalSeparator());

    String prefixAndNumber = "(^|" + boundary+ ")" +
        "([^" + Matcher.quoteReplacement(digit + zero + groupSep + decSep + moneySep) + "']*('[^']*')?)*" +
        "[" + Matcher.quoteReplacement(digit + zero + groupSep + decSep + moneySep + exp) + "]+";

    return numberFormat.toLocalizedPattern().
        replaceAll(prefixAndNumber, "$0" + groups.toString()).
           replaceAll("¤¤", Matcher.quoteReplacement(coinCode())).
           replaceAll("¤", Matcher.quoteReplacement(coinSymbol()));
}}
项目:myfaces-trinidad    文件:NumberConverter.java   
private void _setUpDecimalSymbolFormatProperties(
  DecimalFormatSymbols symbols,
  RequestContext reqCtx,
  Locale locale
  )
{
  if (reqCtx != null)
  {
    char ch = (char) 0;

    if ((ch = reqCtx.getDecimalSeparator()) != (char)0)
      symbols.setDecimalSeparator(ch);

    if ((ch = reqCtx.getNumberGroupingSeparator()) != (char)0)
      symbols.setGroupingSeparator(ch);

  }
  else
  {
    if (_LOG.isWarning())
    {
      _LOG.warning("NULL_REQUESTCONTEXT", locale.toString());
      }
  }
}
项目:myfaces-trinidad    文件:NumberConverter.java   
private void _setCurrencyInformation(
  RequestContext context,
  DecimalFormatSymbols symbols)
{
  String currencyCode = _getCurrencyCode(context);

  // currencyCode is set we honour currency code.
  if (currencyCode != null)
  {
    symbols.setCurrency(Currency.getInstance(currencyCode));
    return;
  }

  if (getCurrencySymbol() != null)
  {
    symbols.setCurrencySymbol(getCurrencySymbol());

     // Loggin at level INFO - shows up by default - so use fine.
    _LOG.fine("Using currency symbol as currecny code evaluates to null");
  }
  // currency symbol will now default based on the locale.
}
项目:myfaces-trinidad    文件:NumberConverter.java   
private void _setCurrencyFormattingProperties(
  RequestContext context,
  NumberFormat numberFormatter
 )
{
  // Useless if... should be instanceof DecimalFormat
  // Potential ClassCastException before the change
  //if (numberFormatter instanceof NumberFormat)
  if (numberFormatter instanceof DecimalFormat)
  {
    DecimalFormat dfmt = (DecimalFormat)numberFormatter;
    DecimalFormatSymbols symbols = dfmt.getDecimalFormatSymbols();
    _setCurrencyInformation(context, symbols);
    dfmt.setDecimalFormatSymbols(symbols);
  }
  else
  {  //string cat at compile time.
    _LOG.warning("NUMBER_NOT_DECIMALFORMAT_IGNORE_CURRENCY");
  }
}
项目:jdk8u-jdk    文件:NumberFormatProviderImpl.java   
private NumberFormat getInstance(Locale locale,
                                        int choice) {
    if (locale == null) {
        throw new NullPointerException();
    }

    LocaleProviderAdapter adapter = LocaleProviderAdapter.forType(type);
    String[] numberPatterns = adapter.getLocaleResources(locale).getNumberPatterns();
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
    int entry = (choice == INTEGERSTYLE) ? NUMBERSTYLE : choice;
    DecimalFormat format = new DecimalFormat(numberPatterns[entry], symbols);

    if (choice == INTEGERSTYLE) {
        format.setMaximumFractionDigits(0);
        format.setDecimalSeparatorAlwaysShown(false);
        format.setParseIntegerOnly(true);
    } else if (choice == CURRENCYSTYLE) {
        adjustForCurrencyDefaultFractionDigits(format, symbols);
    }

    return format;
}
项目:nfse    文件:DoubleConversor.java   
public String toString(Object obj){
  DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ROOT);
  symbols.setDecimalSeparator('.');
  symbols.setGroupingSeparator(','); 

  DecimalFormat formatDecimal = new DecimalFormat("#0.00", symbols);
  formatDecimal.setRoundingMode(RoundingMode.HALF_UP);
  return formatDecimal.format((Double) obj);
}
项目:meuboleto    文件:InterpretadorCodigoBarras.java   
public static String parseToCash( String value) {
    double temp = parseToDouble(value);
    String pattern = "###,###.00";
    DecimalFormatSymbols ds = new DecimalFormatSymbols();
    ds.setDecimalSeparator(',');
    ds.setGroupingSeparator('.');
    DecimalFormat df = new DecimalFormat(pattern,ds);
    df.setGroupingUsed(true);
    return df.format(temp);
}
项目:rapidminer    文件:NumericToFormattedNominal.java   
@Override
public void init() throws OperatorException {
    int localeIndex = getParameterAsInt(PARAMETER_LOCALE);
    Locale selectedLocale = Locale.US;
    if ((localeIndex >= 0) && (localeIndex < availableLocales.size())) {
        selectedLocale = availableLocales.get(getParameterAsInt(PARAMETER_LOCALE));
    }

    int formatType = getParameterAsInt(PARAMETER_FORMAT_TYPE);
    switch (formatType) {
        case FORMAT_TYPE_NUMBER:
            this.numberFormat = NumberFormat.getNumberInstance(selectedLocale);
            break;
        case FORMAT_TYPE_INTEGER:
            this.numberFormat = NumberFormat.getIntegerInstance(selectedLocale);
            break;
        case FORMAT_TYPE_CURRENCY:
            this.numberFormat = NumberFormat.getCurrencyInstance(selectedLocale);
            break;
        case FORMAT_TYPE_PERCENT:
            this.numberFormat = NumberFormat.getPercentInstance(selectedLocale);
            break;
        case FORMAT_TYPE_PATTERN:
            String formatString = getParameterAsString(PARAMETER_PATTERN);
            // the following line only works for Java Versions >= 6
            // this.numberFormat = new DecimalFormat(formatString,
            // DecimalFormatSymbols.getInstance(selectedLocale));
            this.numberFormat = new DecimalFormat(formatString, new DecimalFormatSymbols(selectedLocale));
            break;
    }

    this.numberFormat.setGroupingUsed(getParameterAsBoolean(PARAMETER_USE_GROUPING));
}
项目:rapidminer    文件:Tools.java   
public static void setFormatLocale(Locale locale) {
    FORMAT_LOCALE = locale;
    NUMBER_FORMAT = NumberFormat.getInstance(locale);
    INTEGER_FORMAT = NumberFormat.getIntegerInstance(locale);
    PERCENT_FORMAT = NumberFormat.getPercentInstance(locale);
    FORMAT_SYMBOLS = new DecimalFormatSymbols(locale);
}
项目:jmt    文件:VerboseCSVMeasureOutputReader.java   
/**
 * Builds a new CSV measure reader
 * @param measureCsvFile the measure csv file. Muse be a valid file
 * @param logDecimalSeparator the decimal separator
 * @param logCsvDelimiter the CSV delimiter
 */
public VerboseCSVMeasureOutputReader(File measureCsvFile, String logDecimalSeparator, String logCsvDelimiter) {
    this.measureCsvFile = measureCsvFile;
    this.logCsvDelimiter = logCsvDelimiter;
    DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US);
    dfs.setDecimalSeparator(logDecimalSeparator.charAt(0));
    numberParser = new DecimalFormat("#.#", dfs);
    fileSize = measureCsvFile.length();
}
项目:jmt    文件:Burst.java   
/**
 * Returns this distribution's short description
 * @return distribution's short description
 */
@Override
public String toString() {
    DecimalFormat df = new DecimalFormat("#.############");
    df.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ENGLISH));
    Double probability = (Double) parameters[0].getValue();
    return "burst" + "(" + df.format(probability) + "," + parameters[2].getValue() + "," + parameters[4].getValue() + ")";
}
项目:jmt    文件:Distribution.java   
/**
 * Helper method used to formats given number into string according to default rules.
 * @param d double to be converted
 * @return string representation of given number
 */
protected String FormatNumber(double d) {
    DecimalFormat nf = new DecimalFormat();
    nf.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ENGLISH));
    String ret = null;
    // If module of number is greater than 1e-3 or lesser than 1e3 uses ordinary notation
    if (Math.abs(d) > 1e-3 && Math.abs(d) < 1e3 || d == 0) {
        nf.applyPattern("#.###");
        ret = nf.format(d);
    } else {
        nf.applyPattern("0.00E00");
        ret = nf.format(d);
    }
    return ret;
}
项目:jmt    文件:LDStrategyEditor.java   
/**
 * Helper method used to formats given number into string according to default rules.
 * @param d double to be converted
 * @return string representation of given number
 */
protected String FormatNumber(double d) {
    DecimalFormat nf = new DecimalFormat();
    nf.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ENGLISH));
    String ret = null;
    // If module of number is greater than 1e-4 or lesser than 1e4 uses ordinary notation
    if (Math.abs(d) > 1e-4 && Math.abs(d) < 1e4 || d == 0) {
        nf.applyPattern("#.####");
        ret = nf.format(d);
    } else {
        nf.applyPattern("0.00E00");
        ret = nf.format(d);
    }
    return ret;
}
项目:adyen-android    文件:AmountUtil.java   
public static String format(long amountValue, int exponent, Locale locale) {
    String valueString;
    if (exponent > 0) {
        final String sign = (amountValue < 0) ? "-" : "";
        long absAmountValue = Math.abs(amountValue);
        long power = 1;
        for (int i = 0; i < exponent; i++) {
            power *= 10;
        }
        if (locale != null) {
            DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale);
            String highValue = NumberFormat.getInstance(locale).format((absAmountValue / power));
            valueString = String.format("%s%s%s%0" + exponent + "d", sign, highValue, dfs.getDecimalSeparator(),
                    (absAmountValue % power));
        } else {
            valueString = String.format("%s%d.%0" + exponent + "d", sign, (absAmountValue / power),
                    (absAmountValue % power));
        }
    } else {
        if (locale != null) {
            valueString = NumberFormat.getInstance(locale).format(amountValue);
        } else {
            valueString = String.valueOf(amountValue);
        }
    }
    return valueString;
}
项目:gdl2    文件:DvQuantity.java   
@Override
public String toString() {
    DecimalFormat format = new DecimalFormat();
    format.setMinimumFractionDigits(precision);
    format.setMaximumFractionDigits(precision);
    DecimalFormatSymbols dfs = format.getDecimalFormatSymbols();
    dfs.setDecimalSeparator(DECIMAL_SEPARATOR);
    format.setDecimalFormatSymbols(dfs);
    format.setGroupingUsed(false);
    return format.format(magnitude) + ((unit == null || unit.isEmpty()) ? "" : "," + getUnit());
}
项目:sonar-coverage-evolution    文件:CoverageUtils.java   
public static String formatPercentage(double d) {

    // Defining that our percentage is precise down to 0.1%
    DecimalFormat df = new DecimalFormat("0.0");

    // Protecting this method against non-US locales that would not use '.' as decimal separation
    DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
    decimalFormatSymbols.setDecimalSeparator('.');
    df.setDecimalFormatSymbols(decimalFormatSymbols);

    // Making sure that we round the 0.1% properly out of the double value
    df.setRoundingMode(RoundingMode.HALF_UP);
    return df.format(d);
  }
项目:holon-vaadin7    文件:NumberField.java   
/**
 * Setup user input validation allowed symbols according to current Locale and number type
 */
protected void setupLocaleSymbolsInputValidation() {

    Locale locale = LocalizationContext.getCurrent().filter(l -> l.isLocalized()).flatMap(l -> l.getLocale())
            .orElse(getLocale());
    if (locale == null) {
        // use default
        locale = Locale.getDefault();
    }

    // check grouping
    boolean useGrouping = true;
    if (getInternalField().getConverter() instanceof StringToNumberConverter) {
        NumberFormat nf = ((StringToNumberConverter<?>) getInternalField().getConverter()).getNumberFormat(locale);
        if (nf != null) {
            useGrouping = nf.isGroupingUsed();
        }
    }

    DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);

    char[] symbols = null;
    if (useGrouping) {
        if (TypeUtils.isDecimalNumber(getType())) {
            symbols = new char[] { dfs.getGroupingSeparator(), dfs.getDecimalSeparator() };
        } else {
            symbols = new char[] { dfs.getGroupingSeparator() };
        }
    } else {
        if (TypeUtils.isDecimalNumber(getType())) {
            symbols = new char[] { dfs.getDecimalSeparator() };
        }
    }

    getInternalField().setAllowedSymbols(symbols);
}
项目:OpenDA    文件:SimpleLeastSquaresCostFunctionWithState.java   
private String printNumber(double value) {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    DecimalFormat formatFloat = new DecimalFormat("0.###", symbols);
    DecimalFormat formatExponent = new DecimalFormat("0.###E0", symbols);

    if (Math.abs(value) > 0.01 && Math.abs(value) < 1000.0 || value == 0.0) {
        return formatFloat.format(value);
    } else {
        return formatExponent.format(value);
    }
}
项目:OpenDA    文件:SimpleLeastSquaresCostFunction.java   
private String printNumber(double value) {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    DecimalFormat formatFloat = new DecimalFormat("0.###", symbols);
    DecimalFormat formatExponent = new DecimalFormat("0.###E0", symbols);

    if (Math.abs(value) > 0.01 && Math.abs(value) < 1000.0 || value == 0.0) {
        return formatFloat.format(value);
    } else {
        return formatExponent.format(value);
    }
}
项目:OpenDA    文件:PrintNumber.java   
public static String printNumber(double value) {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    DecimalFormat formatFloat = new DecimalFormat("0.###", symbols);
    DecimalFormat formatExponent = new DecimalFormat("0.###E0", symbols);

    if (Math.abs(value) > 0.01 && Math.abs(value) < 1000.0 || value == 0.0) {
        return formatFloat.format(value);
    } else {
        return formatExponent.format(value);
    }
}
项目:openjdk-jdk10    文件:Formatter.java   
private static char getZero(Locale l) {
    if ((l != null) && !l.equals(Locale.US)) {
        DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l);
        return dfs.getZeroDigit();
    } else {
        return '0';
    }
}
项目:OpenJSharp    文件:Formatter.java   
private static char getZero(Locale l) {
    if ((l != null) && !l.equals(Locale.US)) {
        DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l);
        return dfs.getZeroDigit();
    } else {
        return '0';
    }
}
项目:java-tools    文件:CalendarBase.java   
public String toTimeString(String decimal_format) {
StringBuffer s = new StringBuffer();
s.append( new DecimalFormat("00", new DecimalFormatSymbols(java.util.Locale.US)).format( (long)hour) );
s.append(":");
s.append( new DecimalFormat("00", new DecimalFormatSymbols(java.util.Locale.US)).format( (long)minute) );
s.append(":");
s.append( new DecimalFormat("00", new DecimalFormatSymbols(java.util.Locale.US)).format( (long)second) );
if( partsecond > 0 && partsecond < 1) {
  String sPartSecond = new DecimalFormat(decimal_format, new DecimalFormatSymbols(java.util.Locale.US)).format( partsecond );
  s.append( "." );
  s.append( sPartSecond.substring( 2, sPartSecond.length() ) );
}
if( hasTZ == TZ_UTC ) {
  s.append("Z");
}
else if( hasTZ == TZ_OFFSET ) {
  int absOffsetTZ = offsetTZ;

     if (offsetTZ == 0) {
       s.append("Z");
     }
  else {
       if (offsetTZ < 0) {
      s.append("-");
      absOffsetTZ = -offsetTZ;
    }
    else
      s.append("+");
    s.append(new DecimalFormat("00", new DecimalFormatSymbols(java.util.Locale.US)).format(absOffsetTZ / 60));
    s.append(":");
    s.append(new DecimalFormat("00", new DecimalFormatSymbols(java.util.Locale.US)).format(absOffsetTZ % 60));
     }
}
return s.toString();
 }
项目:openjdk-jdk10    文件:Helpers.java   
/**
 * @return a number formatter instance which prints numbers in a human
 * readable form, like 9_223_372_036_854_775_807.
 */
public static NumberFormat numberFormatter() {
    DecimalFormat df = new DecimalFormat();
    DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
    dfs.setGroupingSeparator('_');
    dfs.setDecimalSeparator('.');
    df.setDecimalFormatSymbols(dfs);
    return df;
}