Convert float to integer in Rust

double b = a / 100000; b = (int) b; b *= 100000; 

How does the above C code convert to Rust? Especially line number 2, which rounds the number.

+7
rust
source share
3 answers

In particular, line # 2, which rounds the number.

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


But here is the Rust equivalent of your exact code (if a is of 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:

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

If you want to round, not just take the integer part, you can use the round f64 method:

 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 these methods to precisely control what is happening, rather than relying on the cast. From the book Rust we can learn:

Casting from float to integer will round the float to zero.

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

  • ... express your intention in code
  • ... have valid semantics, even if the Rust compiler changes casting semantics
+14
source share

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

 let b = (a / 100000.0) as i64; 
+3
source share

This is an example of a round in Rust. You must write the numerical constants according to the type they are: for example, if d is f64, and you want to multiply it by 10, then the correct convention is to write: d * 10.0 instead of: d * 10

and explicitly determine the type of your variable to make the round function available in these cases.

 let a = 2e50; let mut b : f64 = a / 100000.0; b = b.round(); println!("{}", b); 
+2
source share

All Articles