Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert float to integer in Rust

Tags:

rust

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.

like image 628
exebook Avatar asked May 29 '16 05:05

exebook


People also ask

How do you convert float to int in Rust?

To convert an integer to a float in Rust, use as f64 . This is a useful means to convert from various interchangeable types, you can use inline also.

Can you convert float to integer?

A float value can be converted to an int value no larger than the input by using the math. floor() function, whereas it can also be converted to an int value which is the smallest integer greater than the input using math. ceil() function.

How do you convert values to floats?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

Can float convert to int C++?

Use Direct Assignment to Convert Float to Int The conversion between the float and int values can be done using the assignment operator. In this case, the float variable will be implicitly converted to the int type, and the value will be narrowed down to the second type, losing all digits after the decimal point.


1 Answers

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
like image 171
Lukas Kalbertodt Avatar answered Sep 20 '22 17:09

Lukas Kalbertodt