官术网_书友最值得收藏!

Formatting numbers and strings

The @printf macro from the Printf package (we'll look deeper into macros in Chapter 7, Metaprogramming in Julia) takes a format string and one or more variables to substitute into this string while being formatted. It works in a manner similar to printf in C. You can write a format string that includes placeholders for variables, for example, as follows:

julia> name = "Pascal" 
julia> using Printf 
julia> @printf("Hello, %s \n", name) # returns Hello, Pascal 

Because @printf now lives in another package, you have to do this using Printf first (prior to 1.0, it belonged to Base).

If you need a string as the return value, use the macro @sprintf.

The following formatting.jl script shows the most common formats:

using Printf 
# d for integers: 
@printf("%d\n", 1e5) #> 100000 
x = 7.35679 
# f = float format, rounded if needed: 
@printf("x = %0.3f\n", x) #> 7.357 
aa = 1.5231071779744345 
bb = 33.976886930000695 
@printf("%.2f %.2f\n", aa, bb) #> 1.52 33.98 
# or to create another string: 
str = @sprintf("%0.3f", x) 
show(str) #> "7.357" 
println() 
# e = scientific format with e: 
@printf("%0.6e\n", x) #> 7.356790e+00 
# c = for characters: 
@printf("output: %c\n", 'α') #> output: α 
# s for strings: 
@printf("%s\n", "I like Julia") 
# right justify: 
@printf("%50s\n", "text right justified!") 
# p for pointers: 
@printf("a pointer: %p\n", 1e10) #> a pointer: 0x00000002540be400 
 

The following output is obtained upon running the preceding script:

100000 
x = 7.357 
1.52 33.98 
"7.357" 
7.356790e+00 
output: α 
I like Julia 
                   text right justified! 
a pointer: 0x00000002540be400 

A special kind of string is VersionNumber, which the form v"0.3.0" (note the preceding v), with optional additional details. They can be compared, and are used for Julia's versions, but also in the package versions and dependency mechanism of Pkg (refer to the Packages section of Chapter 1, Installing the Julia Platform). If you have the code that works differently for different versions, use something as follows:

if v"0.5" <= VERSION < v"0.6-" 
# do something specific to 0.5 release series 
end

主站蜘蛛池模板: 龙川县| 开平市| 白山市| 开阳县| 都江堰市| 安平县| 灯塔市| 金山区| 常山县| 沧州市| 高雄县| 沙湾县| 华安县| 土默特右旗| 丰都县| 洪湖市| 旌德县| 南澳县| 年辖:市辖区| 资阳市| 博爱县| 肃北| 孟州市| 筠连县| 东至县| 余姚市| 秀山| 宁波市| 仙桃市| 枣阳市| 井冈山市| 密山市| 苍溪县| 望都县| 鄄城县| 海宁市| 玉田县| 蒙自县| 牡丹江市| 辛集市| 姜堰市|