Sunday, December 3, 2023

PHP string to JavaScript number

I had the following JS/PHP code:

<?php $maxSalePrice = 20000; ?>
const salePrice = $('#product-price').val();
const maxSalePrice = "<?php echo $maxSalePrice; ?>";
if(salePrice > maxSalePrice) {
    alert("Sale price can be at most " + maxSalePrice);
}

I tested the code with salePrice of  200, 2000, 20000, the code allowed it and when I used 200000, the code showed the alert message, as it should. However, when I entered 500, it alerted again, but 500 is clearly less than 20000, right?

The problem is that salePrice is a string because it is obtained from a form input and form inputs are strings by default. echo $maxSalePrice also returns a string. Therefore the comparison is not 500 > 20000 but "500" > "20000", which is a lexicographical comparison. Since the first character '5' is larger than '2', "500" is larget than "20000". We should use the JS Number() function to convert strings to numbers:

const salePrice = Number($('#product-price').val());
const maxSalePrice = Number("<?php echo $maxSalePrice; ?>");
if(salePrice > maxSalePrice) {
    alert("Sale price can be at most " + maxSalePrice);
}

No comments:

Post a Comment