Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Spring Framework | Web Services | BioInformatics | Java Server Faces | Jboss 3.0 tutorial | Hibernate 3.0 | XML
 
 
Hot Web Programming Job

 

Tutorial Categories: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML

[an error occurred while processing this directive]

Java: Converting Numbers to Strings

Vanilla Java: Converting numbers to strings is easy. You can do almost everything with concatenation, but can get more control using alternatives. The first choice after concatentation has been DecimalFormat, but as soon as the Java 5 format() and printf() methods are better documented, they are a better second choice.

Converting Anything to String describes how to convert objects to String.

Number to string conversion alternatives

  • Concatenation (+): Anything concatenated to a string is converted to string (eg, "weight = " + kilograms).
  • java.text.DecimalFormat gives you precise control over the formating of numbers (number of decimal places, scientific notation, locale formatting, ...).
  • Individual wrapper class methods, eg, Integer.toString(i). concatenation works as well for the simple cases, but there are some interesting additional conversions here.
  • printf(), added in Java 5, uses a format for conversion.
  • No conversion required. Some common system methods will take any type and convert it, eg, System.out.println().

Concatenation (+)

The most common idiom to convert something to a string is to concatenate it with a string. If you just want the value with no additional text, concatenate it with the empty string, one with no characters in it ("").

If either operand of a concatenation is a string, the other operand is converted to string, regardless of whether it is a primitive or object type.

int x = 42;
String s;
s = x;             // ILLEGAL
s = "" + x;        // Converts int 42 to String "42"
s = x + " is OK";  // Assigns "42 is OK" to s.
s = "" + 3.5;      // Assigns "3.5" to s
s = "" + 1.0/3.0;  // Assigns "0.3333333333333333" to s

Precision. The problem with floating-point numbers by concatenation is that you have no control over the number of decimal places the conversion chooses for you, as you can see in the above example.

java.text.DecimalFormat

The java.text.DecimalFormat class provides many ways to format numbers into strings, including number of fraction digits, using a currency symbol ($12.35), scientific notation (3.085e24), percentage scaling (33%), locale which defines national formatting options (3,000.50 or 3.000,50 or 3'000,50 or ...), patterns for positive, zero, and negative numbers, etc. These notes show only how to specify the number of fraction digits. Check the Java API documentation for other options.

First, create a DecimalFormat object which specifies the format of the number. The zero before the decimal point means that at least one digit is produced, even if it is zero. The zeros after the decimal point specify how many fraction digits are produced. Then call the format() method of that object, passing the numeric value to be converted.

The string that is returned by the format() will not contain additional text, other than an optional currency or percent sign. Specifically, it can not be used to pad numbers on the left with blanks for use in right alignment of a column of numbers. Use printf() for this.

This program uses the same formatting object many times.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
// File:   formatTest/FormatTest.java
// Description: Test default and DecimalFormat formatting.
// Author: Michael Maus
// Date:   2000-10-27, 2000-11-07, 2005-02-13

import java.text.DecimalFormat;

public class FormatTest {
    public static void main(String[] args) {
        DecimalFormat twoPlaces = new DecimalFormat("0.00");
        for (int i=1; i<=10; i++) {
            double val = 1.0 / i; 
            System.out.println("1/" + i + " = " + twoPlaces.format(val) + ", " + val);
        }
    }
}    

Produces this output. The first floating point number is converted by a 2 decimal place DecimalFormat object and the second is the default conversion.

1/1 = 1.00, 1.0
1/2 = 0.50, 0.5
1/3 = 0.33, 0.3333333333333333     // Round down.
1/4 = 0.25, 0.25
1/5 = 0.20, 0.2
1/6 = 0.17, 0.16666666666666666    // Round up.
1/7 = 0.14, 0.14285714285714285
1/8 = 0.12, 0.125                  // Half-even round down.
1/9 = 0.11, 0.1111111111111111
1/10 = 0.10, 0.1

Rounding by the half even algorithm

Floating-point numbers may be rounded when they are converted to string (default conversion, DecimalFormat or the Math.round method, etc). Rounding uses the half even method which rounds

  • To the nearest neighbor.
  • If the number is exactly between its neighbors, it is rounded to its even neighbor. The reason middle values are rounded to the even value, instead of up as is commonly done, is to prevent an accumulation of errors.

Examples rounding to an integer: 3.1 rounds to 3, 3.8 rounds to 4, 3.5 rounds to 4, but 4.5 also rounds to 4, 5.5 rounds to 6.

StringBuffer and StringBuilder append() methods - like concatenation

The most efficient way to build strings from parts is to use StringBuffer (all versions, synchronized), or the essential identical StringBuilder (Java 5, unsynchronized and therefore slightly faster than StringBuffer). Their many append() methods take numbers and perform default conversions to string before appending them to their current value.

StringBuilder sb = new StringBuilder();
int i = 42;
sb.append("Answer = ");
sb.append(i);            // Converts i to string and appends to end.
sb.append(", ");
sb.append(1.0/3.0);
String s = s.toString(); // s is "Answer = 42, 0.3333333333333333"

Numeric objects: Integer, Double, BigDecimal, BigInteger, ...

Concatenation works with all objects, not just numbers. When Java needs to convert an object to a String, it calls the object's toString() method. Because every class (object type) has the class Object as an ancestor, every class inherits Object's toString() method. This will do something to generate a string from an object, but it will not always be very useful. Many classes override toString() to do something better. When you write a class whose objects might be converted to a String, write a toString method.

Various numeric class conversion methods

[This will describe the Integer, etc wrapper class methods, as well as the BigInteger and BigDecimal conversion methods.]

printf()

Java 5 added the format() and printf() methods to various classes. These convert number according to a format string. There are no notes on it here yet.

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

0 comments so far (
post your own) View All Comments Latest 10 Comments:
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification

Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.