Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing two integers doesn't print as a decimal number in Rust

Tags:

rust

I'm learning Rust, but when I print a decimal number, only the integer part is printed, not the decimal part:

fn main(){     println!("{:.3}", 22/7); } // This only show 3 

but when I print the decimal number explicitly, it works correctly:

fn main(){     println!("{:.3}", 0.25648); } // this print 0.256 
like image 956
plafhz Avatar asked Jan 30 '16 03:01

plafhz


People also ask

Does integer division truncate or round?

Integer division rounds towards zero. This means, for example, that the result of the integer division 7 / 5 would have the real number 1.4 as an intermediate result and rounded in the direction of 0 would result in 1 .

How do you convert int to float 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.

How is integer division done?

The % (integer divide) operator divides two numbers and returns the integer part of the result. The result returned is defined to be that which would result from repeatedly subtracting the divisor from the dividend while the dividend is larger than the divisor.

How does integer division work how is it different from float division?

Float division: gives a decimal answer. Integer division: gives the answer in whole numbers (the division result is rounded to the nearest whole number).


2 Answers

Just like in C and C++, dividing integers results in another integer. Try this C++ program to see:

#include <iostream>  using namespace std;  int main() {     cout << 22 / 7 << endl;            // 3     cout << 22.0 / 7.0 << endl;        // 3.14286 } 

Similarly in Rust, you need to specify both numbers as floats instead, which is done by putting a decimal anywhere in the number. Try this Rust equivalent of the above program:

fn main() {     println!("{:.3}", 22 / 7);         // 3     println!("{:.3}", 22.0 / 7.0);     // 3.143 } 

If you have variables, you can convert them with as to either f32 or f64, depending on your needs:

fn main() {     let x = 22;     println!("{:.3}", x / 7);          // 3     println!("{:.3}", x as f32 / 7.0); // 3.143 } 
like image 125
George Hilliard Avatar answered Oct 21 '22 14:10

George Hilliard


When you are working with integer variables and do not have the option to add decimal points you can convert the integer variables into floats using the as keyword:

fn main() {     let a = 42;     let b = 23;     let c = a / b;  // integer division     let d = a as f64 / b as f64;  // cast both variables to float before division     println!("integer division: {}\nfloat division: {}", c, d); } 

This returns the following values:

integer division: 1 float division: 1.826086956521739 
like image 33
m00am Avatar answered Oct 21 '22 15:10

m00am