在Julia中插入时如何格式化字符串? [英] How do you format a string when interpolated in Julia?
本文介绍了在Julia中插入时如何格式化字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python 3中,我会
In Python 3, I would
print_me = "Look at this significant figure formatted number: {:.2f}!".format(floating_point_number)
print(print_me)
或
print_me = f"Look at this significant figure formatted number: {floating_point_number:.2f}!"
print(print_me)
在朱莉娅
print_me = "Look at this significant figure formatted number: $floating_point_number"
print(print_me)
但这会产生说出的声音
Look at this significant figure formatted number: 61.61616161616161
我如何让Julia限制显示的小数位数?请注意,据我所知,使用@printf
宏排除了要打印的字符串的必要存储.
How do I get Julia to restrict the number of decimal places it displays? Note that the necessary storage of the string to be printed, to my knowledge, rules out using the @printf
macro.
这有效,但在样式上似乎不正确.
This works, but does not seem stylistically correct.
floating_point_number = round(floating_point_number,2)
print_me = "Look at this significant figure formatted number: $floating_point_number"
print(print_me)
推荐答案
您可以使用标准库包Printf
中的@sprintf
宏.这将返回一个字符串,而不仅仅是将其打印为@printf
.
You can use @sprintf
macro from the standard library package Printf
. This returns a string rather than just printing it as @printf
.
using Printf
x = 1.77715
print("I'm long: $x, but I'm alright: $(@sprintf("%.2f", x))")
输出:
I'm long: 1.77715, but I'm alright: 1.78
这篇关于在Julia中插入时如何格式化字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文