-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormatFloatInJava.java
More file actions
55 lines (44 loc) · 1.93 KB
/
FormatFloatInJava.java
File metadata and controls
55 lines (44 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Formatter;
/**
* Java program to format float or double to String in Java. In this Java
* example, you will learn how to display a floating point number up-to 2 or 3
* decimal places.
*
* @author Javin Paul
*/
public class FormatFloatInJava {
public static void main(String args[]) {
// First task - format a floating point number up-to 2 decimal places
float pi = 3.1428733f;
// From Java 5, String has a format() method
String str = String.format("%.02f", pi);
System.out.println("formatted float up to 2 decimals " + str);
// If you just want to display, you can combine above two
// by using printf()
// syntax of formatting will remain same
// this will display floating point number up-to 3 decimals
System.out.printf("floating point number up-to 3 decimals : %.03f %n",
pi);
// Alternatively you can also use Formatter class to
// format floating point numbers
// Allocate a Formatter on the StringBuilder
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
// Send all outputs to StringBuilder
// format() has the same syntax as printf()
formatter.format("%.4f", pi); // 4 decimal places
System.out.println("Value of PI up to four decimals : "
+ formatter.toString());
formatter.close();
// Similarly you can format double to String in Java
double price = 20.25;
System.out.printf("Value of double up-to 2 decimals : %.2f", price);
// best way to format floating point numbers in Java
// beware it also round the numbers
DecimalFormat df = new DecimalFormat("#.##");
String formatted = df.format(2.456345);
System.out.println(formatted); //prints 2.46
}
}