Printf
Printf.@printf
— 巨集@printf([io::IO], "%Fmt", args...)
使用 C printf
格式規範字串列印 args
。選擇性地,可以將 IO
傳遞為第一個參數以重新導向輸出。
範例
julia> @printf "Hello %s" "world"
Hello world
julia> @printf "Scientific notation %e" 1.234
Scientific notation 1.234000e+00
julia> @printf "Scientific notation three digits %.3e" 1.23456
Scientific notation three digits 1.235e+00
julia> @printf "Decimal two digits %.2f" 1.23456
Decimal two digits 1.23
julia> @printf "Padded to length 5 %5i" 123
Padded to length 5 123
julia> @printf "Padded with zeros to length 6 %06i" 123
Padded with zeros to length 6 000123
julia> @printf "Use shorter of decimal or scientific %g %g" 1.23 12300000.0
Use shorter of decimal or scientific 1.23 1.23e+07
julia> @printf "Use dynamic width and precision %*.*f" 10 2 0.12345
Use dynamic width and precision 0.12
有關格式的系統性規範,請參閱 這裡。另請參閱 @sprintf
以將結果作為 String
取得,而不是列印出來。
注意事項
Inf
和 NaN
對於旗標 %a
、%A
、%e
、%E
、%f
、%F
、%g
和 %G
會一致地印成 Inf
和 NaN
。此外,如果浮點數與兩個可能的輸出字串的數值距離相等,則會選擇距離零較遠的輸出字串。
範例
julia> @printf("%f %F %f %F", Inf, Inf, NaN, NaN)
Inf Inf NaN NaN
julia> @printf "%.0f %.1f %f" 0.5 0.025 -0.0078125
0 0.0 -0.007812
從 Julia 1.8 開始,%s
(字串)和 %c
(字元)寬度使用 textwidth
計算,例如忽略零寬度字元(例如用於變音符號的組合字元),並將某些「寬」字元(例如表情符號)視為寬度 2
。
動態寬度規格說明符,例如 %*s
和 %0*.*f
,需要 Julia 1.10。
Printf.@sprintf
— 巨集@sprintf("%Fmt", args...)
傳回 @printf
格式化的輸出作為字串。
範例
julia> @sprintf "this is a %s %15.1f" "test" 34.567
"this is a test 34.6"