Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rust - How does one round a floating point number to a specified number of digits?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

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

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);
}

playground

This prints 12.34567 12.35000.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...