rust - How to convert f32 to String with dynamic precision?
问题描述
In my rust code I have a function which takes a float and precision as args. The function should return the formatted string. However, I am not sure how I can format with dynamic precision,
fn convert(val: f32, precision: i16) -> String {
format!("{:.2}", val) // The 2 should be replaced with precision
}
// convert(1.2345, 1) -> 1.2
// convert(1.2345, 2) -> 1.23
解决方案
According to the documentation:
There are three possible ways to specify the desired precision:
An integer
.N
:the integer
N
itself is the precision.An integer or name followed by dollar sign
.N$
:use format argument
N
(which must be ausize
) as the precision.An asterisk
.*
:
.*
means that this{...}
is associated with two format inputs rather than one: the first input holds theusize
precision, and the second holds the value to print. Note that in this case, if one uses the format string{<arg>:<spec>.*}
, then the<arg>
part refers to the value to print, and the precision must come in the input preceding<arg>
.
That is, you can use:
fn convert(val: f32, precision: usize) -> String {
format!("{:.prec$}", val, prec = precision)
}
fn main() {
println!("{}", convert(3.14, 0));
println!("{}", convert(3.14, 1));
println!("{}", convert(3.14, 2));
println!("{}", convert(3.14, 3));
}
推荐阅读
- json - Instagram API 上缺少 JSON 字段
- java - 尝试与 azure AuthenticationResult 连接,但出现错误 java.lang.NoClassDefFoundError: com/nimbusds/jwt/JWTParser
- windows - 无法创建 Azure 容器实例 (Windows)
- c# - 如何使用 C# Interop 在 Excel 中创建漏斗图?
- python - Django Form循环遍历表单字段,但在html行中显示每个字段的1
- html - 如何避免电子邮件客户端中的剪辑
- sql - 我怎样才能改进这个 sql 查询?
- css - 为什么我为 wordpress 主题定制的 CSS 在 cpanel 中不起作用?
- android - 将顶部栏添加到底部导航视图项
- python - 如何快速将 ndarray 的每个元素与排序列表/数组的每个元素进行比较?