- 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
Vertically align numeric values in Java using Formatter
To vertically align numeric values in Java, use Formatter. For working with Formatter class, import the following package.
import java.util.Formatter;
Take an array −
double arr[] = { 2.5, 4.8, 5.7, 6.5, 9.4, 8.4, 9.5, 10.2, 11.5 };
While displaying this double array values, use the %f to set spaces −
for (double d : arr) { f.format("%12.2f %12.2f %12.2f
", d, Math.ceil(d), Math.floor(d)); }
Above, we have also set the decimal places i.e. 12.2f is for 2 decimal places.
The following is an example −
Example
import java.util.Formatter; public class Demo { public static void main(String[] argv) throws Exception { double arr[] = { 2.5, 4.8, 5.7, 6.5, 9.4, 8.4, 9.5, 10.2, 11.5 }; Formatter f = new Formatter(); f.format("%12s %12s %12s
", "Points1", "Points2", "Points3"); System.out.println("The point list...
"); for (double d : arr) { f.format("%12.2f %12.2f %12.2f
", d, Math.ceil(d), Math.floor(d)); } System.out.println(f); } }
Output
The point list... Points1 Points2 Points3 2.50 3.00 2.00 4.80 5.00 4.00 5.70 6.00 5.00 6.50 7.00 6.00 9.40 10.00 9.00 8.40 9.00 8.00 9.50 10.00 9.00 10.20 11.00 10.00 11.50 12.00 11.00
- Related Articles
- How to left align components vertically using BoxLayout with Java?
- How to align JLabel text vertically top in Java?
- Display just hour and minute using Formatter in Java
- Display complete date and time information using Formatter in Java
- Format Output with Formatter in Java
- How can I vertically align elements in a div?
- Using underscore in Numeric Literals in Java
- Java Program to display table with columns in the output using Formatter
- List out the default values of numeric and non-numeric primitive data types in Java?
- Formatter Specifier for Octal and Hexadecimal in Java
- Vertically align the entire grid inside the container with CSS
- Java Program to create custom DateTime formatter
- How to set only numeric values for edittext in Android using Kotlin?
- How to center align component using BoxLayout with Java?
- Sorting objects by numeric values - JavaScript

Advertisements