鸿蒙NEXT开发温度转换工具类TempUtil(ArkTs)

/**
 * 温度转换工具类,支持华氏度与摄氏度相互转换
 * author: CSDN-鸿蒙布道师
 * since: 2025/04/29
 */
export class TempUtil {

  /**
   * 将华氏度转换为摄氏度
   * 公式:C = (F - 32) × (5 / 9)
   *
   * @param fahrenheit 华氏度值
   * @param precision  保留的小数位数,默认为 2
   * @returns 摄氏度值
   */
  static fahrenheitToCelsius(fahrenheit: number, precision: number = 2): number {
    if (typeof fahrenheit !== 'number' || isNaN(fahrenheit)) {
      throw new Error('无效的华氏度数值');
    }

    const celsius = (fahrenheit - 32) * (5 / 9);
    return parseFloat(celsius.toFixed(precision));
  }

  /**
   * 将摄氏度转换为华氏度
   * 公式:F = C × (9 / 5) + 32
   *
   * @param celsius 摄氏度值
   * @param precision 保留的小数位数,默认为 2
   * @returns 华氏度值
   */
  static celsiusToFahrenheit(celsius: number, precision: number = 2): number {
    if (typeof celsius !== 'number' || isNaN(celsius)) {
      throw new Error('无效的摄氏度数值');
    }

    const fahrenheit = celsius * (9 / 5) + 32;
    return parseFloat(fahrenheit.toFixed(precision));
  }

}

代码如下:
/**
 * 温度转换工具类,支持华氏度与摄氏度相互转换
 * author: CSDN-鸿蒙布道师
 * since: 2025/04/29
 */
export class TempUtil {

  /**
   * 将华氏度转换为摄氏度
   * 公式:C = (F - 32) × (5 / 9)
   *
   * @param fahrenheit 华氏度值
   * @param precision  保留的小数位数,默认为 2
   * @returns 摄氏度值
   */
  static fahrenheitToCelsius(fahrenheit: number, precision: number = 2): number {
    if (typeof fahrenheit !== 'number' || isNaN(fahrenheit)) {
      throw new Error('无效的华氏度数值');
    }

    const celsius = (fahrenheit - 32) * (5 / 9);
    return parseFloat(celsius.toFixed(precision));
  }

  /**
   * 将摄氏度转换为华氏度
   * 公式:F = C × (9 / 5) + 32
   *
   * @param celsius 摄氏度值
   * @param precision 保留的小数位数,默认为 2
   * @returns 华氏度值
   */
  static celsiusToFahrenheit(celsius: number, precision: number = 2): number {
    if (typeof celsius !== 'number' || isNaN(celsius)) {
      throw new Error('无效的摄氏度数值');
    }

    const fahrenheit = celsius * (9 / 5) + 32;
    return parseFloat(fahrenheit.toFixed(precision));
  }

}

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值