---
title: "java 摄氏度  华氏度 转换"
author: "onlyor"
date: "2012-11-24T09:53:53Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2012-11-24T09:53:53Z"
id: 1734376
url: "https://onlyor.iteye.com/blog/1734376"
---

```
import java.math.BigDecimal;


public class Util {

    public static void main(String[] args) {
        System.out.println("摄氏度 转 华氏度： " + centigrade2Fahrenheit(10,1));
        System.out.println("华氏度 转 摄氏度： " + fahrenheit2Centigrade(10,5));
    }


    /**
     * 
     * <p>华氏度  = 32 + 摄氏度 × 1.8。</p>
     * @param degree 需要转换的温度
     * @param scale 保留的小数位
     * @return
     */
    public static double centigrade2Fahrenheit(double degree,int scale) {
        double d = 32 + degree * 1.8;
        return new BigDecimal(d).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    
    /**
     * 
     * <p>摄氏度  = (华氏度 - 32) ÷ 1.8。</p>
     * @param degree 需要转换的温度
     * @param scale 保留的小数位
     * @return
     */
    public static double fahrenheit2Centigrade(double degree, int scale) {
        double d = (degree - 32) / 1.8;
        return new BigDecimal(d).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
```