Convert decimal feet to feet and inches?

2019-08-01 12:23发布

问题:

How would I go about converting a measurement from, for example, 12.5 feet to 12ft 6in? How would I created that second number which reads only the decimal place when multiplying by 12?

right now I have double Measurement01 using other variables and some math to get me the feet in decimals. I send that to a textview with farf.setText(Measurement01 + " " + "ft");

Any help would be appreciated!

回答1:

Substract the integer portion:

float measurement = 12.5;
int feet = (int)measurement;
float fraction = measurement - feet;
int inches = (int)(12.0 * fraction);


回答2:

Quite simply, where length is the floating point length:

int feet = (int)length;
int inches = (length - feet) * 12.0;
: :
farf.setText (feet + " ft, " + inches + " inches");


回答3:

Building on @Ry4an's answer:

//... Other code above

float Measurement01 = 12.5;
int feet = (int)Measurement01;
float fraction = Measurement01 - feet;
int inches = (int)(12.0 * fraction);

// Display like: 2.5 = 2 ft 6 in, 0.25 = 3 in, 6.0 = 6 ft
farf.setText((0 != feet ? feet + " ft" : "") + (0 != inches ? " " + inches + " in" : ""));