Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting float value from integers

How can I get a float or real value from integer division? For example:

double result = 30/233;

yields zero. I'd like the value with decimal places.

How can I then format so only two decimal places display when used with a string?

like image 453
4thSpace Avatar asked Apr 18 '09 05:04

4thSpace


Video Answer


1 Answers

You could just add a decimal to either the numerator or the denominator:

double result = 30.0 / 233;
double result = 30 / 233.0;

Typecasting either of the two numbers also works.

As for the second part of the question, if you use printf-style format strings, you can do something like this:

sprintf(str, "result = %.2f", result);

Bascially, the ".2" represents how many digits to output after the decimal point.

like image 143
hbw Avatar answered Sep 20 '22 15:09

hbw