How can I round a given number, for example 1.17 to 1.20 not 1.0 or 2.0. I was trying to print a list of centimeters, feet and inches from 4 ft to 7 ft. I've got the centimeters, and feet part working but the inches part is not as intended.
Here is the function I use to generate the list and log the results
private void print() {
final float oneInch = 2.54f;
final float oneFt = 30.48f;
final float end = oneInch * 12 * 7;
float start = oneInch * 12 * 4;
int cm;
int ft;
float in;
StringBuilder sb = new StringBuilder();
DecimalFormat decimalFormat = new DecimalFormat("#.##");
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
while (start <= end) {
if (sb.length() > 0) {
sb.replace(0, sb.length(), "");
}
cm = (int) start;
sb.append(cm);
sb.append(" cm, ");
ft = (int) (start / oneFt);
in = Float.valueOf(decimalFormat.format(start / oneFt - ft));
if (in >= 1.0f) {
++ft;
in = 0f;
}
sb.append(ft);
sb.append(" ft ");
if (in > 0) {
sb.append(String.valueOf(in).replace("0.", ""));
}
start += oneInch;
Log.i("measure", sb.toString());
}
}
Here is the logged values
121 cm, 4 ft
124 cm, 4 ft 08
127 cm, 4 ft 17
129 cm, 4 ft 25
it is printing as 4 ft 08, how can I print the inches part as whole numbers, like this?
121 cm, 4 ft
124 cm, 4 ft 1
127 cm, 4 ft 2
129 cm, 4 ft 3
Do not use Strings for numeric operations. When doing math, use math operators and math functions:
in = (start / oneFt - ft) * 12;
You don't need to round your numbers at all. Let the DecimalFormat do the rounding:
if (in > 0) {
sb.append(decimalFormat.format(in));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.