Tabnine Logo
NumberFormat
Code IndexAdd Tabnine to your IDE (free)

How to use
NumberFormat
in
java.text

Best Java code snippets using java.text.NumberFormat (Showing top 20 results out of 16,470)

Refine searchRefine arrow

  • DecimalFormat
  • DecimalFormatSymbols
  • Format
  • BigDecimal
  • Locale
  • JFrame
origin: stackoverflow.com

 float a = 8250325.12f;
float b = 4321456.31f;
float c = a + b;
System.out.println(NumberFormat.getCurrencyInstance().format(c));
// prints $12,571,782.00 (wrong)

BigDecimal a1 = new BigDecimal("8250325.12");
BigDecimal b1 = new BigDecimal("4321456.31");
BigDecimal c1 = a1.add(b1);
System.out.println(NumberFormat.getCurrencyInstance().format(c1));
// prints $12,571,781.43 (right)
origin: log4j/log4j

/**
 * Format number.
 * @param n number to format, may not be null.
 * @return formatted value.
 */
private static synchronized String formatNumber(final Object n) {
  Locale currentLocale = Locale.getDefault();
  if (currentLocale != numberLocale || numberFormat == null) {
    numberLocale = currentLocale;
    numberFormat = NumberFormat.getInstance(currentLocale);
  }
  return numberFormat.format(n);
}
origin: apache/rocketmq

public static String offset2FileName(final long offset) {
  final NumberFormat nf = NumberFormat.getInstance();
  nf.setMinimumIntegerDigits(20);
  nf.setMaximumFractionDigits(0);
  nf.setGroupingUsed(false);
  return nf.format(offset);
}
origin: redisson/redisson

  public String nextAnchor(Node node) {
    this.lastAnchorId++;
    NumberFormat format = NumberFormat.getNumberInstance();
    format.setMinimumIntegerDigits(3);
    format.setMaximumFractionDigits(0);// issue 172
    format.setGroupingUsed(false);
    String anchorId = format.format(this.lastAnchorId);
    return "id" + anchorId;
  }
}
origin: junit-team/junit4

/**
 * Returns the formatted string of the elapsed time.
 */
public String elapsedTimeAsString(long runTime) {
  return NumberFormat.getInstance().format((double) runTime / 1000);
}
origin: spring-projects/spring-framework

@Test
public void parseLocalizedBigDecimalNumber3() {
  String bigDecimalAsString = "3.14159265358979323846";
  NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH);
  Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class, numberFormat);
  assertEquals(new BigDecimal(bigDecimalAsString), bigDecimal);
}
origin: stackoverflow.com

 BigDecimal numerator = new BigDecimal(5);
BigDecimal denominator = new BigDecimal(2);

//In current scenario
  Locale locale = new Locale("de", "DE");
  NumberFormat format = DecimalFormat.getInstance(locale);
  String number = format.format(numerator.divide(denominator));
  System.out.println("Parsed value is "+number); 

The output here will be 2,5
origin: stackoverflow.com

 double d = 1.2345;
DecimalFormat df = new DecimalFormat("#0.00");
System.out.println(df.format(d)); // will print 1.23
d = 3.400;
System.out.println(df.format(d)); // will print 3.40
d = 3.456;
System.out.println(df.format(d)); // will print 3.46

BigDecimal b = new BigDecimal(0.20001);
System.out.println(df.format(b)); // will print 0.20
origin: stackoverflow.com

  DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
  df.setParseBigDecimal(true);
  BigDecimal bd = (BigDecimal) df.parseObject(numberString);
  System.out.println(bd.toString());
} catch (ParseException e) {
  e.printStackTrace();
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
try {
  BigDecimal bd1 = new BigDecimal(nf.parse(numberString).toString());
  System.out.println(bd1.toString());
} catch (ParseException e) {
  e.printStackTrace();
origin: stackoverflow.com

 BigDecimal a = new BigDecimal("-54125412512.231515235346");
BigDecimal b = new BigDecimal("-1231254125412512.231515235346");

NumberFormat formatter = new DecimalFormat("#,###");
formatter.setRoundingMode(RoundingMode.HALF_UP);
formatter.setMinimumFractionDigits(4);
formatter.setMaximumFractionDigits(4);
System.out.println("Number : " + formatter.format(a));
System.out.println("Number : " + formatter.format(b));
origin: stackoverflow.com

 public static String readableFileSize(long size) {
  if(size <= 0) return "0";
  final String[] units = new String[] { "B", "kB", "MB", "GB", "TB" };
  int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
  return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
origin: stackoverflow.com

static DecimalFormat decConv = new DecimalFormat("00.00");
private JButton convertDegreesToDecimal;
private JButton convertDecimalToDegreesButton;
 JFrame window = new JFrame();
 window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 window.setVisible(true);
 window.setLayout(new GridLayout(2, 1));
 decimalPanel.setLayout(new FlowLayout());
 decimalInput = new JFormattedTextField(
   DecimalFormat.getInstance());
 decimalInput.setColumns(5);
 convertDecimalToDegreesButton = new JButton("convert");
 degreesPanel.setLayout(new FlowLayout());
 degreesInput = new JFormattedTextField(
   NumberFormat.getIntegerInstance());
 degreesInput.setColumns(2);
 minutesInput = new JFormattedTextField(
   NumberFormat.getIntegerInstance());
 minutesInput.setColumns(2);
 secondsInput = new JFormattedTextField(
   DecimalFormat.getInstance());
 secondsInput.setColumns(5);
origin: stackoverflow.com

String number = "12345678910111213141516000";
 BigDecimal bd = new BigDecimal(number);
 DecimalFormat formatter = new DecimalFormat("#,###,###,###.#####");
 System.out.println("You want it : " + formatter.format(bd));
 Number num = formatter.parse(number);
 System.out.println("You don't want it : " + formatter.format(num));
origin: stackoverflow.com

String s = "100000";
 Locale dutch = new Locale("nl", "NL");
 NumberFormat numberFormatDutch = NumberFormat.getCurrencyInstance(dutch);
 String c = numberFormatDutch.format(new BigDecimal(s.toString()));
 System.out.println("Currency Format: "+ c);
 try {
   Number  d = numberFormatDutch.parse(c);
   BigDecimal bd = new BigDecimal(d.toString());
   System.out.println(bd);
 } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
 }
origin: stackoverflow.com

  decimal = Character.toString( format.getDecimalFormatSymbols().getDecimalSeparator() );
  setColumns( format.toPattern().length() );
  setHorizontalAlignment(JFormattedTextField.TRAILING);
  setText( format.format(0.0) );
public void setText(String text)
  Number number = format.parse(text, new ParsePosition(0));
        String text = format.format( format.parse( sb.toString() ) );
        super.replace(fb, 0, doc.getLength(), text, a);
      String text = format.format( format.parse( sb.toString() ) );
      super.replace(fb, 0, doc.getLength(), text, null);
  panel.add( abm );
  JFrame frame = new JFrame("ABMTextField");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.add( panel );
  frame.setSize(200, 200);
origin: stanfordnlp/CoreNLP

/**
 * Returns a String summarizing recall that will print nicely.
 */
public String getRecallDescription(int numDigits) {
 NumberFormat nf = NumberFormat.getNumberInstance();
 nf.setMaximumFractionDigits(numDigits);
 return nf.format(getRecall()) + "  (" + tpCount + "/" + (tpCount + fnCount) + ")";
}
origin: stackoverflow.com

 public static boolean isNumber(String s){
  try{
    Locale l = Locale.getDefault();
    DecimalFormat df = new DecimalFormat("###.##;-##.##");
    Number n = df.parse(s);
    String sb = df.format(n);
    return sb.equals(s);
  }
  catch(Exception e){
    return false;
  }
}
origin: stackoverflow.com

 NumberFormat formatter = NumberFormat.getNumberInstance(Locale.GERMANY);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumIntegerDigits(2);
formatter.setMinimumFractionDigits(2);
System.out.println((formatter.format(new BigDecimal(100)))); // prints "100,00"
origin: stackoverflow.com

 double myValue = 0.00000021d;

DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); //340 = DecimalFormat.DOUBLE_FRACTION_DIGITS

System.out.println(df.format(myValue)); //output: 0.00000021
origin: stackoverflow.com

 Locale l = Locale.getDefault();
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(l);

DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setGroupingSeparator('.'); // setting the thousand separator
// symbols.setDecimalSeparator(','); optionally setting the decimal separator

formatter.setDecimalFormatSymbols(symbols);
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);

String formattedString = formatter.format(yourDouble);
java.textNumberFormat

Javadoc

The abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales have number formats, and what their names are.

NumberFormat helps you to format and parse numbers for any locale. Your code can be completely independent of the locale conventions for decimal points, thousands-separators, or even the particular decimal digits used, or whether the number format is even decimal.

To format a number for the current locale, use one of the factory class methods:

 
myString = NumberFormat.getInstance().format(myNumber); 

If you are formatting multiple numbers, it is more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.

 
NumberFormat nf = NumberFormat.getInstance(); 
for (int i = 0; i < a.length; ++i) { 
output.println(nf.format(myNumber[i]) + "; "); 
} 

To format a number for a different locale, specify it in the call to getInstance.

 
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH); 

You can also use a NumberFormat to parse numbers:

 
myNumber = nf.parse(myString); 

Use #getInstance or #getNumberInstance to get the default number format. Use #getIntegerInstance to get an integer number format, #getCurrencyInstance to get the currency number format, and #getPercentInstance to get a format for displaying percentages.

You can also control the display of numbers with methods such as setMinimumFractionDigits. If you want even more control over the format or parsing, or want to give your users more control, you can try casting the NumberFormat you get from the factory methods to a DecimalFormat. This will work for the vast majority of locales; just remember to put it in a try block in case you encounter an unusual one.

NumberFormat is designed such that some controls work for formatting and others work for parsing. For example, setParseIntegerOnly only affects parsing: If set to true, "3456.78" is parsed as 3456 (and leaves the parse position just after '6'); if set to false, "3456.78" is parsed as 3456.78 (and leaves the parse position just after '8'). This is independent of formatting.

You can also use forms of the parse and format methods with ParsePosition and FieldPosition to allow you to:

  • progressively parse through pieces of a string;
  • align the decimal point and other areas.
For example, you can align numbers in two ways:
  1. If you are using a monospaced font with spacing for alignment, you can pass the FieldPosition in your format call, with field = INTEGER_FIELD. On output, getEndIndex will be set to the offset between the last character of the integer and the decimal. Add (desiredSpaceCount - getEndIndex) spaces to the front of the string.
  2. If you are using proportional fonts, instead of padding with spaces, measure the width of the string in pixels from the start to getEndIndex. Then move the pen by (desiredPixelWidth - widthToAlignmentPoint) before drawing the text. This also works where there is no decimal but possibly additional characters before or after the number, for example with parentheses in negative numbers: "(12)" for -12.

Synchronization

Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

DecimalFormat

DecimalFormat is the concrete implementation of NumberFormat, and the NumberFormat API is essentially an abstraction of DecimalFormat's API. Refer to DecimalFormat for more information about this API.

Most used methods

  • format
    Formats a number into a supplied buffer. The number must be a subclass of Number. Instances of Byte,
  • getInstance
  • setMaximumFractionDigits
    Sets the maximum number of fraction digits that are printed when formatting. If the maximum is less
  • getNumberInstance
    Returns a NumberFormat for formatting and parsing numbers for the specified locale.
  • parse
  • setGroupingUsed
    Sets whether this number format formats and parses numbers using a grouping separator.
  • setMinimumFractionDigits
    Sets the minimum number of fraction digits that are printed when formatting.
  • getPercentInstance
    Returns a NumberFormat for formatting and parsing percentage values for the given locale.The NumberF
  • setMinimumIntegerDigits
    Sets the minimum number of integer digits that are printed when formatting.
  • getIntegerInstance
    Returns a NumberFormat for formatting and parsing integers for the specified locale.
  • getCurrencyInstance
    Returns a NumberFormat for formatting and parsing currency values for the specified locale.
  • setParseIntegerOnly
    Specifies if this number format should parse numbers only as integers or else as any kind of number.
  • getCurrencyInstance,
  • setParseIntegerOnly,
  • setMaximumIntegerDigits,
  • getMaximumFractionDigits,
  • clone,
  • setCurrency,
  • getMinimumFractionDigits,
  • setRoundingMode,
  • getAvailableLocales,
  • parseObject

Popular in Java

  • Updating database using SQL prepared statement
  • getSupportFragmentManager (FragmentActivity)
  • requestLocationUpdates (LocationManager)
  • notifyDataSetChanged (ArrayAdapter)
  • Runnable (java.lang)
    Represents a command that can be executed. Often used to run code in a different Thread.
  • Date (java.util)
    A specific moment in time, with millisecond precision. Values typically come from System#currentTime
  • Hashtable (java.util)
    A plug-in replacement for JDK1.5 java.util.Hashtable. This version is based on org.cliffc.high_scale
  • LinkedList (java.util)
    Doubly-linked list implementation of the List and Dequeinterfaces. Implements all optional list oper
  • Options (org.apache.commons.cli)
    Main entry-point into the library. Options represents a collection of Option objects, which describ
  • BasicDataSource (org.apache.commons.dbcp)
    Basic implementation of javax.sql.DataSource that is configured via JavaBeans properties. This is no
  • Top 12 Jupyter Notebook extensions
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now