How do you format a string when interpolated in Julia?
在Python 3中,我愿意
1 2 | print_me ="Look at this significant figure formatted number: {:.2f}!".format(floating_point_number) print(print_me) |
要么
1 2 | print_me = f"Look at this significant figure formatted number: {floating_point_number:.2f}!" print(print_me) |
在朱莉娅
1 2 | print_me ="Look at this significant figure formatted number: $floating_point_number" print(print_me) |
但这会产生说法
1 | Look at this significant figure formatted number: 61.61616161616161 |
如何让Julia限制它显示的小数位数? 请注意,据我所知,要打印的字符串的必要存储使用
这有效,但在风格上似乎不正确。
1 2 3 | floating_point_number = round(floating_point_number,2) print_me ="Look at this significant figure formatted number: $floating_point_number" print(print_me) |
您可以使用标准库包
1 2 3 | using Printf x = 1.77715 print("I'm long: $x, but I'm alright: $(@sprintf("%.2f", x))") |
输出:
1 | I'm long: 1.77715, but I'm alright: 1.78 |
除了@ niczky12的答案,您还可以使用专为此类事物设计的格式化包!
1 2 3 4 | Pkg.add("Formatting") using Formatting: printfmt x = 1.77715 printfmt("I'm long: $x, but I'm alright: {:.2f}", x) |
输出:
1 | I'm long: 1.77715, but I'm alright: 1.78 |
虽然它仍在进行中(我需要添加一些单元测试,并且我想添加一个Python 3.6样式模式),但您也可以使用我的StringUtils.jl包,它添加了C和Python之类的格式,Swift 样式插值,表情符号,LaTex和Html以及Unicode命名字符到字符串文字。
1 2 3 4 5 6 7 | Pkg.clone("https://github.com/ScottPJones/StringUtils.jl") Pkg.checkout("StringUtils") using StringUtils x = 1.77715 print(u"I'm long: \(x), but I'm alright: \%.2f(x)") |
输出:
1 | I'm long: 1.77715, but I'm alright: 1.78 |