如何将浮点数四舍五入到指定的位数? [英] How does one round a floating point number to a specified number of digits?

查看:59
本文介绍了如何将浮点数四舍五入到指定的位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 Rust 中的 f64 浮点数四舍五入到指定位数?

How does one round a f64 floating point number in Rust to a specified number of digits?

推荐答案

如果您只想将其用于显示目的,请使用 格式化语法内置于 println!().例如,要打印四舍五入到 2 个小数位的数字,请使用 {:.2} 格式说明符:

If you want this just for display purposes, use the formatting syntax built into println!(). For example, to print a number rounded to 2 decimal places use the {:.2} format specifier:

fn main() {
    let x = 12.34567;
    println!("{:.2}", x);
}

如果要将四舍五入的数字放入字符串中,请使用 format!().

If you want to put the rounded number in a string, use the format!() macro.

如果你想对一个数字进行四舍五入并将结果作为另一个数字返回,然后将该数字乘以给定的 10 次幂,调用 round,并除以相同的幂,例如要四舍五入到 2 个小数位,使用 102 = 100.

If you want to round a number and get the result back as another number, then multiply the number by the given power of 10, call round, and divide by the same power, e.g. to round to 2 decimal places, use 102 = 100.

fn main() {
    let x = 12.34567_f64;
    let y = (x * 100.0).round() / 100.0;

    println!("{:.5} {:.5}", x, y);
}

游乐场

这会打印 12.34567 12.35000.

如果在编译时不知道小数位数,可以使用 powi 以有效地计算相关功率.

If the number of decimal places isn't known at compile time, one could use powi to efficiently compute the relevant power.

请注意,这将分解为非常大的数字;具体来说,大于 std::f64::MAX/power(其中 power 是 10 的幂,例如上例中的 100)将在乘法中变为无穷大,之后保持无穷大.但是,f64 不能表示大于 253 的数字的任何小数位(即它们始终是整数),因此可以将如此大的数字特殊情况下只返回自身.

Note that this will breakdown for very large numbers; specifically, numbers larger than std::f64::MAX / power (where power is the power of ten, e.g. 100 in the example above) will become infinity in the multiplication, and remain infinity after. However, f64 cannot represent any fractional places for numbers larger than 253 (i.e. they're always integers), so one can special case such large numbers to just return themselves.

这篇关于如何将浮点数四舍五入到指定的位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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