//克到磅和盎司
public static String convertGramsToPoundsAndOunces(String grams) {
double weightInKG = Double.parseDouble(grams) / 1000;
double pounds = weightInKG / 0.45359237;
double lbs = Math.floor(pounds);
double fraction = (pounds - lbs) * 16;
return String.valueOf(Math.round(lbs) + "lbs" + " " + String.format("%.1f", new BigDecimal(fraction)) + "oz");
}
//磅数和盎司
public static double convertPoundsToGrams(String pounds, String oz) {
double lbs = 0;
double ounces = 0;
double grams = 0;
try {
if (pounds != null && pounds.trim().length() != 0) {
lbs = Double.parseDouble(pounds);
}
if (oz != null && oz.trim().length() != 0) {
ounces = Double.parseDouble(oz) * 0.062500;
}
grams = (lbs + ounces) / 0.0022046;
return grams;
} catch (NumberFormatException nfe) {
System.err.println("Invalid input.");
}
return grams;
}
我尝试将磅和盎司转换为克数,并通过转换克数显示相同的磅数和盎司。
我输入1磅和0.9盎司转换回克,但当我将克转换回磅和盎司时我得到1磅和1.1磅... [0.2 ounces is getting increased each time
]
答案 0 :(得分:1)
convertPoundsToGrams
返回double
值。要将克数恢复为磅数和盎司,您应该将返回的克(双)值的类型更改为String
的类型,因为convertGramsToPoundsAndOunces
的参数为String
。
试试这个:
double grams = convertPoundsToGrams("1", "0.9");
System.out.println(grams);
String grams2PO = String.valueOf(grams);
System.out.println(convertGramsToPoundsAndOunces(grams2PO));
答案 1 :(得分:0)
适合我:
double grams = convertPoundsToGrams("1", "0.9");
Log.d(TAG, "Grams: " + grams);
Log.d(TAG, "String grams:" + String.valueOf(grams));
String pounds = convertGramsToPoundsAndOunces(String.valueOf(grams));
Log.d(TAG, "Pound/Oz string: " + pounds);
返回的字符串是“1lbs 0.9oz”。
我猜你是如何将convertPoundsToGrams
(返回一个双精度型)的结果转换/传递给convertGramsToPoundsAndOunces
,这需要一个字符串。