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

发布于:2025-05-01 ⋅ 阅读:(15) ⋅ 点赞:(0)
/**
 * 温度转换工具类,支持华氏度与摄氏度相互转换
 * 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));
  }

}