在 Julia 中插值时如何格式化字符串? [英] How do you format a string when interpolated in Julia?

查看:18
本文介绍了在 Julia 中插值时如何格式化字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

In Python 3, I would

print_me = "Look at this significant figure formatted number: {:.2f}!".format(floating_point_number)
print(print_me)

or

print_me = f"Look at this significant figure formatted number: {floating_point_number:.2f}!"
print(print_me)

In Julia

print_me = "Look at this significant figure formatted number: $floating_point_number"
print(print_me)

but this would yield say

Look at this significant figure formatted number: 61.61616161616161

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)

解决方案

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))")

Output:

I'm long: 1.77715, but I'm alright: 1.78

这篇关于在 Julia 中插值时如何格式化字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆