Home> Java> javaTutorial> body text

String's format method formats numbers

巴扎黑
Release: 2016-12-02 09:28:15
Original
2024 people have browsed it

In life, we write numbers in various formats, such as 20:32:32PM, which has the same time, and 122, 223, 223.23, which represents the amount of money. There are also ways to format numbers in java. From java5.0 onwards, You can use the Formatter class in java.util to format numbers. You do not need to inherit this class or call methods in this class, because there is a format() method in String that can also achieve this function.
For example: String.format("String str", number);
This method runs by passing in two or more parameters. The first parameter is a string parameter, and the following parameters are numeric parameters. You can Define the formatting format of the following numbers in the string parameter. In the string, you can also write any string before % and after the % formatting parameter, like this:

public class TestTest { public static void main(String[] args) { System.out.println(String.format("It’s a number%,6.1f",2223223.155)); System.out.println(String.format("It’s a number %,.1f",3223.12)); //%后面可以跟五个部分,但是只有类型部分是必须写的,如上句中的f即为单精度浮点型,还有四个部分按顺序 //分别是可以指定参数的数字(有超过两个参数以上时),特定的类型(如上句中的“,”,或者给输出加上正负号),规定最小字符数(如上面的“6”),“.”符号加上精确度。 } }
Copy after login

The output is

Quote

It's a number2,223,223.2
It's a number 3,223.1



format() method can of course also format the number into time format. The code is as follows:
Please see the code below for details:

import java.util.Date; public class NumGeShiHua { public static void main(String[] args) { String s = String.format("test%,11d, %,.3f.", 1007000, 220000.12352); System.out.println(s); // 输出日期:sunday,Nov28 204, // 特别二的方法,只是为了输出所需输出的日期字符串 int b = 28; int c = 204; String a = String.format("sunday,Nov%d %d", b, c); System.out.println(a); // 把Date类型的变量日期用这样的格式输出,Date是JAVA上表示时间的类, // 所以如果用这种format方法的话,数字与日期时间格式化的主要差别在于日期格式的类型 // 日期格式使用"t"开头的两个字符来表示。例如: String tc = String.format("%tc", new Date());// 这个%tc是用来表示完整的日期和时间。 String tr = String.format("%tr", new Date());// %tr是只表示时间。 // 用%tA%tB%tC来表示周月日; Date today = new Date(); String time2 = String.format("%tA,%tB %tC", today, today, today); // 表达周月日还有另外一种表达方式。 String time = String.format("%tA,%
        
Copy after login
test 1,007,000, 220,000.124. sunday,Nov28 204 现在是日期和时间是 星期三 十一月 30 13:50:24 CST 2016 现在的时间是 01:50:24 下午 今天的日期是 星期三,十一月 20 今天的日期是 星期三,十一月 20
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!