I'm not sure how to make this function return the float
in two decimal places.
float calcPrice(float a, float b, string x) {
if (x == "X") return (a - b) * 7.5;
else return (a - b) * 9.75;
}
I'm not sure how to make this function return the float
in two decimal places.
float calcPrice(float a, float b, string x) {
if (x == "X") return (a - b) * 7.5;
else return (a - b) * 9.75;
}
You can't "truncate" a float. A float does not have something like a "decimal place". what you type into your code is just convencience, the binary representation of floats is completely different: https://en.wikipedia.org/wiki/Single-precision_floating-point_format
If you want to display the float in any way, you can still format it with functions like printf (keep in mind that it is a string after the formatting, not a float).
printf("%.2f", foobar); // prints out foobar with 2 digits
It is also advised to not use floats for monetary calculations. Floats become imprecise with big(ger) numbers due to their small size (even doubles and other floating point formats will eventually run out of precision). Not to mention that floats are prone to rounding errors (again due to their limited size). These errors accumulate quite quickly.
For monetary calculations, you can use fixed point math. With fixed point math you really do have a fixed number of decimal places and the implementation is similar to basic integer math. You simply have to take care of the carry.
See here for more info about fixed point math: Fixed Point Arithmetic in C Programming