The Artima Developer Community
Sponsored Link

Java Buzz Forum
5 examples of formatting float or double numbers to String in Java

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Javin Paul

Posts: 1090
Nickname: javinpaul
Registered: Jan, 2012

Javin Paul is Java Programmer working on Finance domain.
5 examples of formatting float or double numbers to String in Java Posted: Jun 7, 2014 7:51 AM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Javin Paul.
Original Post: 5 examples of formatting float or double numbers to String in Java
Feed Title: Java67
Feed URL: http://www.java67.com/feeds/posts/default?alt=rss
Feed Description: Java and technology tutorials, tips, questions for all programmers.
Latest Java Buzz Posts
Latest Java Buzz Posts by Javin Paul
Latest Posts From Java67

Advertisement
Formatting floating point numbers is a common task in software development and Java programming is no different. You often need to pretty print float and double values up-to 2 to 4 decimal places in console, GUI or JSP pages. Thankfully Java provides lots of convenient methods to format a floating point number up to certain decimal places. For example you can use method printf() to format a float or double number to a output stream. However, it does not return a String. In JDK 1.5, a new static method format() was added to the String class, which is similar to printf(), but returns a String. By the way there are numerous way to format numbers in Java, you can use either DecimalFormat class, or NumberFormat or even Formatter class to format floating point numbers in Java. Coming back to String's format method, here is a quick example of using it :
String strDouble = String.format("%.2f", 1.23456);
This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.2f, f is for floating point number, which includes both double and float data type in Java. Don't try to use "d" for double here, because that is used to format integer and stands for decimal in formatting instruction. By the way there is a catch here, format() method will also arbitrarily round the number. For example if you want to format 1.99999 up-to 2 decimal places then it will return 2.0 rather than 1.99, as shown below.
Read more »

Read: 5 examples of formatting float or double numbers to String in Java

Topic: ActiveMQ – Network of Brokers Explained – Part 4 Previous Topic   Next Topic Topic: DevOps with Apache Tomcat/TomEE and Fabric8

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use