number format 1 « Number Format « Java Data Type Q&A

1. How do I format a number in java?

How do I format a number in java? What are the "Best Practices"? Will I need to round a number before I format it? "32.302342342342343" formatted to "32.30" ".7323" formatted to "0.73" etc.

2. Conditional Number Formatting In Java

How can I format Floats in Java so that the float component is displayed only if it's not zero? For example:

123.45 -> 123.45
99.0   -> 99
23.2   -> 23.2
45.0 ...

3. Parse number with positive/negative prefix from string in java

It's quite straight forward in java to parse number from String, i.e. with Integer.parseInt(s) if string in the format 'n' or '-n', but unfortunately it fails to parse string in the ...

4. Formatting numbers with same amount of padding

I want to format 3 digit floats in Java so they line up vertically such that they look like:

When I use DecimalFormat class, I get close, but I ...

5. Is there anywhere a Java library available that supports exactly the format strings of Excel?

For a Java application that drags data together from some sources and does some calculation itself, we want to offer users the possibility to use their own format strings, and would ...

6. How do I format a number left-padded without using String.format in Java 6?

For example, I need to grab an unknown number, let's say 3, and find the binary (2^3) - 1 times, from 0 to 111 (0-7). Obviously, the number of digits I ...

7. how to set number format to cells using jexcel api

I am writing a excel sheet with various floating values . It is absolutely necessary that i do not lose any decimal point when doing this. I am using this code:


8. How to format message with argument names instead of numbers?

I have something like:

String text = "The user {0} has email address {1}."
// params = { "Robert", "" }
String msg = MessageFormat.format(text, params);
This isn't great for me, because sometimes my translators ...

9. How to avoid Number Format Exception in java?

In my day to day web application development there are many instances where we need to take some number inputs from the user. Then pass on this number input to may ...

10. number format exception

when i am saving the data at that time when i enter mobile no like 1234567891 it is saving properly but when i insert random mno as 4342432435 it giving error ...

11. number format exception

hi my code is giving the error while saving the data. error is coming in DATE i have taken datatype of this DATE as date/ time in ms access DB.i have ...

12. Format numbers in java

How do I get these formats in java? Input:

Output :
I will be always converting one by one number, this was just to get more examples.

13. How can I change 2.5E7 to a normally formatted number?

How can I change 2.5E7 to 2,500,000.00?

14. JXL Number Format and Cell Type

I am using JXL to write an Excel file. The customer wants a certain column to display numbers with one decimal place. They also want the cell types to be "Number". ...

15. How to format numbers with no grouping separator

Hi I'm traying formating BigDecimal value by using DecimalFormat.format() methods. My problem is how to set DecimalFormat exactly DecimalFormatSymbol to format text without any grouping separators. I'd like use simple way, ...

16. Java program to display numbers in calculator format

I need to display numbers in form calculator user enters 6 , 7 , 8 , 9 so it should get displayed in the same way as calculator displays. The numbers ...

17. How to get this number format in java?

Lets say I am having a number as follows :

long number = 32301672060;
I want the following the format for the number :
i.e the last two digits should be separated ...

18. Number formatting in Java

I need the following number format in java:

long a=5000;
Expected output is : 50,00 if
long a = 25624;
Expected output is : 256,24
long a = 614324;
Expected output is
How can I get this ...

19. Java: Format a string as a telephone number

I have an unformatted telephone number string ("5551234567"). I would like to format this string for display purposes in the ui. The number should look like this after format: (555) 123-4567 Sigh..... I ...

20. How to check that the string contains the number format in Java?

I am new to applet concept. I want to implement the one application. The applet have 2 text areas and one button. The first text area is the input(means it contains ...

21. %s in String.format for numbers

Is there any reason not to use %s for the format specifier when formatting numbers if no extra formatting is required? e.g.

int answer = 42;
String text = String.format("The answer is %s", answer);
rather ...

22. Insert variable number of whitespaces in the middle of the string (to format "usage" help)

How to refactor this to be one line?

String format = "%-20s";
System.out.print(String.format(format, "Property name"));
System.out.println(": property value");
Likely I want to have something like this, the question is what format should I use?
System.out.println(String.format(format, "Property ...

23. number formatting

24. Formating a number

25. Number Format Exception

/* try this code... 1. if u have 1000000000099 as a String object, change it to Lang object and then to long 2. if u have 1000000000099 as a Long object chage it to long --- see java.Lang package for details --- */ class help1 { public static void main(String[] args) { String S="1000000000099"; /* trim() to remove extra spaces from ...

26. number formatted is unexpected.

I have a problem to make the number formatted to 2 points. This is the code i use and i expect to get iQ = 0.13 instead of 0.133 using codes below. What is my syntax arror actually? Could anybody tell me? NumberFormat nf; nf = NumberFormat.getInstance(); nf.setMaximumIntegerDigits(2); nf.setMinimumIntegerDigits(2); String iQ = nf.format(iQuan); System.out.println("iQ :"+iQ); Thanks alot.

27. How to format large number correctly?

Hi friends: I want to display a large number to jsp reading from database(Oracle).The number is "1111111111". The number in database is "1111111111" excactly and it is Float (126) . But after it displayed to jsp,it become "1111111112" ?! why JVM auto format Float number? The number "1111111112" is not what I want to see. I use NumberFormat class to format ...

28. Number formatting

Hi, my issue is like this: my application should display numbers the way its in the DB, upto 6 decimal places,if the value is 1.2 it should display only 1.2 and not 1.200000, if its 1.22 it should display 1.22 and not 1.220000. this goes on till 6 deciamal places. i am not sure wether its a java or a java ...

29. Number Formatting

30. Number Format Exception?

31. Number format exception

Hey, I have the following piece of code that i want to convert what i read in from the text file into a binary representation so i can use it to do encryption. It currently looks like this: public static int readFile(String fileName) { int answer; String str = ""; try { // Open stream and reader objects FileInputStream s = ...

32. Lost precision when do number format

33. Format the number in java

Hi Guys, I m writing a java program to get the sequence of number if the from no and to num is given example if i give from 1 to 10 the o/p is: 1 2 3 4 5 6 7 8 9 10 this works fine but whn i enter 0001 to 0010 the o/p is same as of the ...

34. formatting number

Hello, See the Java Source for DecimalFormat(String) Parameter Constructor. It depends on the Locale Object. /** * Creates a DecimalFormat using the given pattern and the symbols * for the default locale. This is a convenient way to obtain a * DecimalFormat when internationalization is not the main concern. *

* To obtain standard formats for a given locale, use ...

35. Formatting Arabic numbers

Hi Edwin, I have a string which contains Arabic numbers and now I want to format it. So I am using NumberFormat class and using its getNumberInstance method. This method returns object of type NumberFormat. I am calling format method on this object, to format this Arabic number, the issue I am facing is format method doesnt accept string value so ...

36. Format number string to include leading zeros

I'm trying to take the input of several JTextField's that contain integers and concatenate them into a formatted String (for both display and to be saved). I'm having trouble getting leading zeros into my string. For example, if the first field contains the number '1', I want it to appear as '001' in my String. I've tried a few things, including ...

37. Number Format

Hi, I am having two formatted numbers to be added Limit1 and Limit2 String Limit1=7,500.00; String Limit2=7,000.00; I have to add these two and get the result as 14,500.00 I followed the normal procedure with for loop and sustring. my code is String aloplimit1=""; for(int i=0;i

38. number formating

I'm having a double value e.g. a)99558669546. b)0.00125 I have to convert these values into String. I need to read the value as-is without any truncation or formatting. For E.g. i do not want 'a' to be formatted in Exponential format (like E9) and i dont want 'b' to be truncated to 0.001 while converting to String. How can I achieve ...

39. Number formatting

I am getting a string with follwing formats 23434 2.32453 223,324,343.34532424 324,343.34532424 2.3453E-01 32,456.9 0 1.0 Note:The Number can be negative also. First I want to check whether the number is postive or negative Secondly I want to round the value to two decimal place. Thirdly I want to display the number in the million format. Regards Asheesh

40. Number Formatting

Hi, Sachin. Maybe something like this? import java.text.*; public class DoubleFormatter { public static final StringBuffer template = new StringBuffer( "0." ); double value; public String round( int places ) { for ( int i = 0; i < places; ++i ) { template.append( "0" ); } DecimalFormat df = new DecimalFormat( template.toString() ); return df.format( value ); } public String ...

42. Number Format

It kinda depends on what you're trying to do. Are you doing a bunch of calculations and want to print the final answer? You want to print intermediate answers? You want to do calculations and round off the answers before you do more calculations (You might run into some inaccuracies that way)? Are you working with money?

43. Number Format

44. Number Format Specifiers

import java.text.NumberFormat; class Test { public static void main(String args[]) { double f = 123456789123.0; // Show the default output. System.out.println("Default output: " + f); // Get a NumberFormat object. NumberFormat nf = NumberFormat.getInstance(); // Set its minimum fractional digits to 2 nf.setMinimumFractionDigits(12); // Display the formatted number System.out.println("Formatted output: " + nf.format(f)); } }

45. How do I print a formatted number?

I feel a bit stupid about this, but I haven't figured out how to printed a formatted number to the console in Java. I was hoping for a "printf" or something like it. Here is a sample of what I'd like to do: public class CtoF { public static void main(String[] args) { for (double c=34; c<44; c+=.1) { double f= ...

46. Number format

47. Formatting numbers in a String

48. number formatting

Hey, I'm new to this forum, but you guys seem helpful, so I'll give it a shot and post my question here: Basically i have a number with two decimals (Currency format), eg 1 000 000.89 dollars that i want to format so that the two decimals are separate from the rest of the number: eg 1 000 000 dollars and ...

49. Number format

50. number format

I have the following code: System.out.println("\nAccount details for:"); System.out.println("********************"); //display Decimal format to two places DecimalFormat twoDecimal = new DecimalFormat ("0.00"); System.out.println("This is the decimal format to two places: "+twoDecimal.format(getBalance( ) ) ); //use BigDecimal to deal with finances BigDecimal amount = new BigDecimal (getBalance( ) ); System.out.println("BigDecimal Amount changed to a String for display: "+amount.toString( ) ); //formating currency i.e ...

51. Numbers formatting

52. Number Format

Ya i have made a mistake by saying an int variable. Anyway again the question is this : When people printing amounts in bills and cheques, they use a standard format to avoid frauds. For an example amount will always display in a fixed number of didgits, assume its 10 digits for a while. So, if the amount to be printed ...

53. Number Format problem

54. How to format the number

float f = 45.789887f; String dropString = "" + f; int pointLocation = dropString.indexOf("."); /**Look at the java.lang.String to figure out the rest... *probably want to create a new string from 0 to an index position. *Then you're left with a string. Look at java.lang.Float if you *want to parse the string further. */

55. Number Format Exceptions in java classes

I'm programming a web application and when I debug it and I'm stepping through it my debugger jumps into the core numeric classes with a lot of number format exceptions. I was wondering if I'm not defining something properly or if this is normal behavior? I get no adverse results, no compiler warnings, no compiler errors, but the debugger seems to ...

56. [SOLVED] Is it my math or my logic/code? Number Formatting difficulties

Hey all, I can't decide what's going wrong here. I'm trying to write a program (for an assignment at school) which times how long the process takes to search a list. I can get the program to run, but I'm getting unexpected results. It's always telling me that it takes 0 ms to run. I don't know if it's my math, ...

57. Number format Problem - Please advise

58. need help formatting numbers as strings

I need to format numbers that are represented as both as ints and doubles. So String1 = "123123123.455" I want to convert to "123,123,123.455" And String2 = "123123123" convert to "123,123,123" What is the best way to do this? I played around with String.format, but I am not sure what the mask would look like.

59. Changing the exponential number into normal readable number format?

Actually in my code, floatValue of BigDecimal was taken. for bigger numbers onwards 17548097, it starts losing its precision and starts giving a difference of value 1. So thats why now i decided to take the doubleValue of BigDecimal. I am just doing this test : but the output i do get is in exponential form. I want to change it ...

60. Number Formatting Issue

The following code generates a NullPointerException: Console Output: [7/30/09 8:57:58:889 CDT] 00000028 ServletWrappe A SRVE0242I: [ResourceManagementEAR] [/ResourceManagement] [ScheduledMonthDisplayServlet]: Initialization successful. [7/30/09 8:57:59:498 CDT] 00000028 SystemOut O B: 990.0 [7/30/09 8:57:59:498 CDT] 00000028 ServletWrappe E SRVE0068E: Could not invoke the service() method on servlet ScheduledMonthDisplayServlet. Exception thrown : java.lang.NullPointerException System.out.println("B: "+taskhours); this.scheduledhoursbyprojectbymonth[i] = Float.parseFloat(decimalFormat.format(taskhours)); System.out.println("A: "+this.scheduledhoursbyprojectbymonth[i]); This is also in the class: ...

61. ghost number format exception

62. number format exception

public class Xcess0740Test { private String functionName= null; private String recordName= null; private static FileInputStream fis740 = null; private static String inputFileName = "D://Atarashii//Java//Apps//v110//Properties//740.txt"; private String serverIp = null; private String port = null; private static FileOutputStream fos750 = null; private static final String outputFileName = "D://Atarashii//Java//Apps//v110//Properties//deucheKeys.txt"; public Xcess0740Test() { super(); // TODO Auto-generated constructor stub } public static void main(String[] ...

63. Number format exception

What have you put into the Set in the first place? If there are Integers in it, there is no need to mess around with the parseInt and toString methods; you simply get the Integer out and can convert it to an int with auto-unboxing if necessary. Your code is poorly formatted, which makes it difficult to read; there should, for ...

64. number format question

may i know what should i do if i want print 0 as 0000 and 11 as 0011 999 as 0999... it seems int a =0000 prints only 0 not the one i want. please let me know how to format these number and let me know if there is any method to accomplish this task.

65. Change Number Format in entire application

What is the easiest way to change the number format throughout a web application. The application consists of JSP pages to display the values. There are java classes to fetch the values from database and some calcuations are done on these values. I want to change the displayed number format Eg. 31,12,000 to 3,112,000

66. Formating formated string back into original number

Right I'm doing a simple application in Netbeans, that deals with large numbers so I want my Text Fields to be Formated. Now right after input of the number to it(when you press enter, or when text field losses focus) I made it that a number is formated. like this number: 213999222 into: 213.999.222 I made it with this code: NumberFormat ...

67. Number Format Exception

Can someone fine the exception with the Integers? I know where it is at, just can't find out how it is happening Exception:type Exception report message description The server encountered an internal error () that prevented it from fulfilling this request. exception java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer InventoryServlets.InvSelect.doPost( InventoryServlets.InvSelect.doGet( javax.servlet.http.HttpServlet.service( javax.servlet.http.HttpServlet.service( org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter( note The full stack trace of the ...

68. Number Format Exception

I am having a jsp page and I am getting the data in the EJB bean using a SQL (script Below) public ArrayList getOrderLines(SotOrderHeaderJavaBean SotOJB) { ArrayList a = new ArrayList(); StringBuffer lineSQL = new StringBuffer(); lineSQL.append("select "); lineSQL.append("product_status,"); lineSQL.append("group_number,"); lineSQL.append("product_id,"); lineSQL.append("bucket_id,"); lineSQL.append("coverage_code,"); lineSQL.append("exclude_line,"); lineSQL.append("bmr,"); lineSQL.append("bmr_usd,"); lineSQL.append("discretionary_disc,"); lineSQL.append("NR_ZB_LOCAL,"); lineSQL.append("quantity,"); lineSQL.append("NVL(nr_zb_local,0)*NVL(quantity,0) "); lineSQL.append("from spt_quote_line "); lineSQL.append("where quote_number = " + Double.parseDouble(SotOJB.getOrderNumber())); lineSQL.append(" ...

69. Why is it throwing "number format exception" ?

Code: //WAP That convert integer value into binary,octal and hexdecimal. import*; class numconv { public static void main(String s[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(; char ch='y'; int opt,num; String bin,oct,hex; do { System.out.println("******* 1: Convert number to Binary format ********"); System.out.println("******* 2: Convert number to Octal format *********"); System.out.println("******* 3: Convert number to Hexadecimal format ***"); System.out.print("\n\n Enter Option ...

70. Format Numbers

71. Number formatting

Java Code: import java.util.Scanner; import java.lang.String; import java.lang.Integer; public class ISBN { public static void main(String[] args) { String isbn; Checksum nisbn; Scanner input = new Scanner(; System.out.print("Enter the first 12 digits of an ISBN as a string: "); isbn =; while (isbn.length() != 12) { System.out.println("That ISBN was not 12 digits long. Please enter a new one: "); isbn ...

72. String and number formatting

73. formatting numbers in output

74. How to change number format of a field programmatically in Jasper?

public void viewReport() { try { String jrxml = getJRXML(); if (cls1.isFileDirectoryExists(jrxml)) { Map params = new HashMap(); params.put("NUMBER_FORMAT", "###,##0.0000"); // just for try JasperDesign jasperDesign = JRXmlLoader.load(jrxml); JRDesignQuery query = new JRDesignQuery(); query.setText(getSQL()); jasperDesign.setQuery(query); JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); Connection jdbcConn = connectMySQL(); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, jdbcConn); JasperViewer.viewReport(jasperPrint, false); } else { cls1.msgBox(null, jrxml + " does not exists", ...

75. catch the number format exception, where to place try

I have a gui in the view package which has the functionality of a mini calculator. Beside of that in the model package i have a Calculator class It works but when i enter a string in number1Textfield i get a NumberFormatException. Thats correct because i want to insert a try/catch statement, but when i insert it, it doens't catch the ...

76. Numbers formatting with printf

Hello there! I'm another Java newbie, and I was just wondering what the magic formula was to make printf spew out my numbers like so: 1 565 434 with a space for every 10^3;10^6;10^9..etc instead of 1565434 and alternatively, how do I achieve the following: 1,565,434.0 (<-- doesnt matter in this case for decimals, was just to show comma's versus dots. ...

77. Number format convertions

If your code runs fine then typing in "s4" and trying to convert that to hex will throw a NumberFormatExcpetion. If you are not getting that then your code is doing something other than what you think. Since you only gave us a snippet we cannot see the whole picture. For example what are numbin and hexbin? I suspect you do ...

78. formatting strings and numbers

79. Dividing a complex number. Need help with the method format.

Okay it's not that I put "null" in that exception. I replaced "null" by putting in a new Complex number that equaled zero, just to see if the error message changed, and it didn't. The error message says: "method must return a result of type Complex". Should I not be using the if statement? What do I do?

80. Why is it throwing "number format exception" ?

Please read following method description from Java Docs : ( It is obvous it throws an exception parseInt : public static int parseInt(String s) throws NumberFormatException Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a ...

81. Number Format Exception

Hi All, I am having a problem while reading data from a text file and trying to insert into database. I have an Excel file and I entered some data into it(this data I have to insert into database later) and then write it into a text file.But when i read this data from text file,I am getting the Number Format ...

82. Changing a number format

83. number format

84. Number format problem

85. Format number

86. Please Help : Format a Positive Real Number

and i sholud Assume that the fractional part F always has no leading zeroes and both F and I have at most five (5) significant digits. If I give an input as Input: 10000.6660 The output should look like .... Output: 6660#.1 and if the input is : Input: 990.0080 The output should be... Output: 80###.99 Input: 101.11111 Output: 11111.101 Input: ...

87. Customize the number format

88. How to make Formatting Numbers in Java?

Hi, I have a problem to format numbers in Java. Suppose I have a number 12345678.9876 I would like to show the number in various format like 1) 12,345,678.9876 2) 12.345.678,9876 3) 12 345 678.9876 4) 12,345,678.99 I am totally puzzled with the NumberFormat class, DecimalFormat class and Locale class. Please give me some very simple code. --Sujoy

89. Number Object Format

In my experience, trying to edit numbers with regexps rather than parsing them and formatting them, is fragile. Sooner or later there's going to be some kind of surprise, due to an input that's outside the range of currently assumed inputs. Parsing/formatting (with standard tools that are usually more formally correct and debugged to a large degree) is usually less fragile ...

90. Number format exception....

Take a look at the string you are attempting to parse. It is not a double -- that's what the exception is trying to tell you. Listen. Edit: BTW Lists are your friends. You don't need to transfer the data to an array -- just use a List. Now the parallel Lists. not so hot...

91. Problems with formating my numbers properly.

Hey I'm currently working on my assignment and part of it asks to output your results. My problem is keeping the bottom numbers aligned with the numbers at the top. I've been looking at NumberFormat but still ain't sure what I'm doing wrong. Basicly I would like to make the output look like this : 0 1 2 3 4 5 ...

92. Number Format Exception

93. Number format problem - Please advise

94. number format exception

i have got the number format exception when trying to convert a string into integer coming from node.gettextcontent(); here is my code where u understand it properly........... "/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package SwingChartsRND; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.jfree.chart.*; import ...

95. Indian Number Format

97. Number formatting

98. Number formatting help

Hi there, I'm having some problem formatting my numerical outputs - all of which are doubles. what I need is to print an integer if the double is a whole number (8.00000 => 8) and print non-whole doubles to 2 decimal places. I have no problem with rounding to 2 decimal places, I have multiple ways of doing that. My problem ...

99. Number Formatting error

100. Number Format Internationalization Doubt

Actually My Doubt was to prevent input of a Specific Character by the User in an Input TextField. As in, I no longer want to allow a "." in the Number Input Field for a German User since his locale specific Decimal Separator is ",". So How do I know before hand what is his Locale Specific Decimal Separator so that ...