Rounding Off Values to Two Decimal Places In calculations

 // Get the values entered by the user
      var lengthFt = Number(document.getElementById('length-ft').value);
      var lengthInch = Number(document.getElementById('length-inch').value);
      var widthFt = Number(document.getElementById('width-ft').value);
      var widthInch = Number(document.getElementById('width-inch').value);

      // Perform calculations
      var length = lengthFt + (lengthInch / 12);
      var width = widthFt + (widthInch / 12);
      var sqrft = length * width;

      sqrft = sqrft.toFixed(2); // Format to two decimal places

      var decimalPart = sqrft.split('.')[1]; // Extract the decimal part
      if (decimalPart.length > 2) {
        // Check if the third decimal place is 5 or greater
        var thirdDecimal = Number(decimalPart.charAt(2));
        if (thirdDecimal >= 5) {
          // Round up the second decimal place
          var secondDecimal = Number(decimalPart.charAt(1));
          secondDecimal += 1;
          sqrft = sqrft.split('.')[0] + '.' + decimalPart.charAt(0) + secondDecimal;
        } else {
          // Keep only the first two decimal places
          sqrft = sqrft.split('.')[0] + '.' + decimalPart.charAt(0) + decimalPart.charAt(1);
        }
      }

Leave a comment

Your email address will not be published. Required fields are marked *