- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Format floating point with Java MessageFormat
To format message with floating point fillers in Java, we use the MessageFormat class. The MessageFormat class gives us a way to produce concatenated messages which are not dependent on the language. The MessageFormat class extends the Serializable and Cloneable interfaces.
Declaration −The java.text.MessageFormat class is declared as follows −
public class MessageFormat extends Format
The MessageFormat.format(pattern, params) method formats the message and fills in the missing parts using the objects in the params array matching up the argument numbers and the array indices.
The format method has two arguments, a pattern and an array of arguments. The pattern contains placeholder in {} curly braces which have a index that indicate the position in the array where the value of the argument is stored, a number argument indicating that the filler is a number and a #.# parameter indicating that the number is a floating point number. They are as follows −
MessageFormat.format("{0,number,#.#} Hellos and {1,number,#.#} Worlds", obj);
Let us see a program to format the message with floating fillers:
Example
import java.text.MessageFormat; public class Example { public static void main(String[] args) throws Exception { Object[] obj = new Object[] { new Float(23.21), new Float(56.86) }; String message = MessageFormat.format("{0,number,#.#} Hellos and {1,number,#.#} Worlds", obj); System.out.println(message); } }
Output
23.2 Hellos and 56.9 Worlds
Note that the Floating numbers have been rounded off one significant digit i.e. 23.21 has been rounded off to 23.2 and 56.86 has been rounded off to 56.9 −
Object[] obj = new Object[] { new Float(23.21), new Float(56.86) };
- Related Articles
- Format currency with Java MessageFormat
- Format floating point number in Java
- Format percentage with MessageFormat class in Java
- Long style format for Date with Java MessageFormat class
- Short Length format for Date with Java MessageFormat class
- Medium length style format for Date with Java MessageFormat class
- Floating-point hexadecimal in Java
- Floating-point conversion characters in Java
- Floating point operators and associativity in Java
- Java program to multiply given floating point numbers
- Java Program to Multiply Two Floating-Point Numbers
- Apply modulus operator to floating-point values in Java
- Signed floating point numbers
- C++ Floating Point Manipulation
- Fixed Point and Floating Point Number Representations
