Convert float to integer in Rust

后端 未结 3 1323
鱼传尺愫
鱼传尺愫 2021-02-03 19:02
double b = a / 100000;
b = (int) b;
b *= 100000;

How the above C code is converted to Rust? Especially the line #2 that rounds the number.

相关标签:
3条回答
  • 2021-02-03 19:18

    To cast a float to an integer, you can use as. For example:

    let b = (a / 100000.0) as i64;
    
    0 讨论(0)
  • 2021-02-03 19:18

    This is an example of round in Rust. You have to write numeric constants right the type they are: for example if d is f64 and you want to multiply it by 10 the right convention is to write: d * 10.0 instead of: d * 10

    and explicitly define the type of your variable to make the round function available in this cases.

    let a = 2e50;
    let mut b : f64 = a / 100000.0;
    b = b.round();
    println!("{}", b);
    
    0 讨论(0)
  • 2021-02-03 19:21

    Especially the line #2 that rounds the number.

    First of all: this is not true. To "round" a real number is to return the nearest integer. You just convert it to int which discards all the non-integer parts.


    But here is the Rust equivalent of your exact code (assuming a has the type f64):

    let b = a / 100_000.0;    // underscore in number to increase readability
    let b = b as i64;
    let b = b * 100_000;
    

    Which, of course, can be written in one line, too:

    let b = ((a / 100_000.0) as i64) * 100_000;
    

    If you wanted to round instead of just taking the integer part, you can use the round method of f64:

    let b = ((a / 100_000.0).round() as i64) * 100_000;
    

    Note that there are also trunc, ceil and floor. You can use one of those methods to exactly control what happens instead of relying on the cast. From the Rust book we can learn:

    Casting from a float to an integer will round the float towards zero.

    This behavior is equivalent to trunc, but if the behavior does matter to you, you should use trunc to ...

    1. ... express your intent in code
    2. ... have valid semantics even if the Rust compiler changes the cast semantics
    0 讨论(0)
提交回复
热议问题