0

// 克 到 磅和盎司

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]

4

2 回答 2

1

convertPoundsToGrams返回double值。要将克返回到磅和盎司,您应该将返回的克(双)值的类型更改为类型 of,String因为convertGramsToPoundsAndOunces有参数 of String

尝试这个:

double grams = convertPoundsToGrams("1", "0.9"); 
System.out.println(grams);
String grams2PO = String.valueOf(grams);
System.out.println(convertGramsToPoundsAndOunces(grams2PO));
于 2013-06-16T15:51:12.517 回答
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,它需要一个字符串。

于 2013-06-16T15:09:10.633 回答