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.
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.
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.
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 typef64
):Which, of course, can be written in one line, too:
If you wanted to round instead of just taking the integer part, you can use the
round
method off64
:Note that there are also
trunc
,ceil
andfloor
. 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:This behavior is equivalent to
trunc
, but if the behavior does matter to you, you should usetrunc
to ...To cast a float to an integer, you can use
as
. For example: