Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

โปรแกรมแปลงอุณหภูมิ - JavaScript

แปลงอุณหภูมิระหว่าง Celsius และ Fahrenheit จากสตริงที่ลงท้ายด้วย C หรือ F

สูตร

  • C → F: (C × 9/5) + 32
  • F → C: (F - 32) × 5/9

ตัวอย่างโค้ด

const temp1 = '37C';
const temp2 = '100F';

const tempConverter = temp => {
  const degree = temp[temp.length - 1];
  let converted;

  if (degree === 'C') {
    converted = (parseInt(temp) * 9 / 5 + 32).toFixed(2) + 'F';
  } else {
    converted = ((parseInt(temp) - 32) * 5 / 9).toFixed(2) + 'C';
  }
  return converted;
};

console.log(tempConverter(temp1)); // 98.60F
console.log(tempConverter(temp2)); // 37.78C

การทำงาน

  • ดึงหน่วยจากตัวอักษรสุดท้าย
  • parseInt(temp) ดึงตัวเลข (ตัดหน่วยทิ้ง)
  • คำนวณตามสูตร แล้ว toFixed(2) ปัดทศนิยม 2 ตำแหน่ง

ผลลัพธ์

98.60F
37.78C