在Python 3中,我愿意
print_me = "Look at this significant figure formatted number: {:.2f}!".format(floating_point_number)
print(print_me)
Run Code Online (Sandbox Code Playgroud)
要么
print_me = f"Look at this significant figure formatted number: {floating_point_number:.2f}!"
print(print_me)
Run Code Online (Sandbox Code Playgroud)
在朱莉娅
print_me = "Look at this significant figure formatted number: $floating_point_number"
print(print_me)
Run Code Online (Sandbox Code Playgroud)
但这会产生说法
Look at this significant figure formatted number: 61.61616161616161
Run Code Online (Sandbox Code Playgroud)
如何让Julia限制它显示的小数位数?请注意,据我所知,要打印的字符串的必要存储使用@printf宏来排除.
这有效,但在风格上似乎不正确.
floating_point_number = round(floating_point_number,2)
print_me = "Look at this significant figure formatted number: $floating_point_number"
print(print_me)
Run Code Online (Sandbox Code Playgroud)
nic*_*y12 20
您可以使用@sprintf标准库包中的宏Printf.这将返回一个字符串,而不仅仅是将其打印出来@printf.
using Printf
x = 1.77715
print("I'm long: $x, but I'm alright: $(@sprintf("%.2f", x))")
Run Code Online (Sandbox Code Playgroud)
输出:
I'm long: 1.77715, but I'm alright: 1.78
Run Code Online (Sandbox Code Playgroud)
Dan*_*ndt 11
除了@ niczky12的答案,您还可以使用专为此类事物设计的格式化包!
Pkg.add("Formatting")
using Formatting: printfmt
x = 1.77715
printfmt("I'm long: $x, but I'm alright: {:.2f}", x)
Run Code Online (Sandbox Code Playgroud)
输出:
I'm long: 1.77715, but I'm alright: 1.78
Run Code Online (Sandbox Code Playgroud)
虽然它仍在进行中(我需要添加一堆单元测试,并且我想添加 Python 3.6 样式模式),但您也可以使用我的StringUtils.jl包,它添加了 C 和 Python 之类的格式化、Swift样式插值、Emoji、LaTex、Html 和 Unicode 命名字符到字符串文字。
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)")
Run Code Online (Sandbox Code Playgroud)
输出:
I'm long: 1.77715, but I'm alright: 1.78
Run Code Online (Sandbox Code Playgroud)