floating point value

Started by
34 comments, last by phil67rpg 10 years, 8 months ago

I am able to input a number like 3.15 into a variable. I want to extract the 3 from the value and use it later. Let me know if you need more info.

Advertisement

cast it to an int.

cool I will try that

In addition to the obvious answer of casting it to an int, you could try passing it to std::floor() in <cmath>, if it's just going to be converted back to a floating point number anyway. Beware, though, that casting to an int always truncates toward zero, while calling std::floor() with a negative parameter will round toward negative infinity. If your floating point number is outside of the range representable by an integer, you must use std::floor().

is there anyway to extract the .51 from a variable.

Subtract the integer part from the value.

well thanks for all the help

Or just try:

3.15 mod 1 = 0.15

3.15 - 0.15 = 3

Since this is C++, there's a handy little C function for this... goes by the name of modf.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

well this code works except that pence outputs 0.2 and I want it to output 2

 
 
float pounds=0, shillings=0, pence = 0;
 
 
float decimal_pounds;
cout << 
 
"Enter decimal pounds: ";
cin >> decimal_pounds;
cout << endl;
pounds=(
 
int)decimal_pounds;
decimal_pounds= decimal_pounds - pounds;
shillings = (
 
int) (decimal_pounds * 20.0);
pence = (
 
float)(decimal_pounds * 20.0)- shillings ;
cout << 
 
"Equivalent in old notation = " << '\x9c' << pounds << "." << shillings << "." << pence << endl;
system (
 
"pause");
 
 
return 0;

This topic is closed to new replies.

Advertisement