Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

java - Why can the String.format("%02d:%02d.%02d") display 3 digits in Android?

The Code A which is from a sample project use "%02d:%02d.%02d" to format a string of time, it seems that it only display two digits for minutes.

Normally, it will display Result A.

Because it only display 2 digits with "%02d:%02d.%02d", I think the App will crash if I run it in a long time , but it can display Result B, why?

Code A

fun fromCountToTimeByInterval(count: Int, interval:Int ) : String {
    val minutes = count * interval / 1000 / 60
    val seconds = count * interval / 1000 % 60
    val milliSeconds = (count * interval % 1000) / 10  
    return String.format("%02d:%02d.%02d", minutes, seconds, milliSeconds)  
}

Result A

50:23.02

Result B

235:14.13
question from:https://stackoverflow.com/questions/65838197/why-can-the-string-format02d02d-02d-display-3-digits-in-android

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to JavaDoc of Java Formatter,

   %[flags][width]conversion

combined with the flag,

Flags

'0' The result will be zero-padded

the width,

Width

The width is the minimum number of characters to be written to the output. For the line separator conversion, width is not applicable; if it is provided, an exception will be thrown.

and the conversion explanation,

If the '0' flag is given, then the locale-specific zero digits are inserted after the sign character, if any, and before the first non-zero digit, until the length of the string is equal to the requested field width.

'd' Formats the argument as a decimal integer. The localization algorithm is applied.
If the '0' flag is given and the value is negative, then the zero padding will occur after the sign.

%02d means a decimal integer where its number of digits is less than two, it will be zero-padded. Otherwise, just print it because the given width 2 means the number of minimum characters to print including zeros, spaces, and digits.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...