//克为磅和盎司

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]

最佳答案

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));

10-08 18:16