Posts

Showing posts with the label Numbers

Converting Hexadecimal To Float In JavaScript

Answer : Another possibility is to parse the digits separately, splitting the string up in two and treating both parts as ints during the conversion and then add them back together. function parseFloat(str, radix) { var parts = str.split("."); if ( parts.length > 1 ) { return parseInt(parts[0], radix) + parseInt(parts[1], radix) / Math.pow(radix, parts[1].length); } return parseInt(parts[0], radix); } var myno = 28.4382; var convno = myno.toString(16); var f = parseFloat(convno, 16); console.log(myno + " -> " + convno + " -> " + f); Try this. The string may be raw data (simple text) with four characters (0 - 255) or a hex string "0xFFFFFFFF" four bytes in length. jsfiddle.net var str = '0x3F160008'; function parseFloat(str) { var float = 0, sign, order, mantissa, exp, int = 0, multi = 1; if (/^0x/.exec(str)) { int = parseInt(str, 16); } else { for (var i = str.len...

Allow 2 Decimal Places In

Answer : Instead of step="any" , which allows for any number of decimal places, use step=".01" , which allows up to two decimal places. More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute If case anyone is looking for a regex that allows only numbers with an optional 2 decimal places ^\d*(\.\d{0,2})?$ For an example, I have found solution below to be fairly reliable HTML: <input name="my_field" pattern="^\d*(\.\d{0,2})?$" /> JS / JQuery: $(document).on('keydown', 'input[pattern]', function(e){ var input = $(this); var oldVal = input.val(); var regex = new RegExp(input.attr('pattern'), 'g'); setTimeout(function(){ var newVal = input.val(); if(!regex.test(newVal)){ input.val(oldVal); } }, 0); }); Update setTimeout is not working correctly anymore for this, maybe browsers have changed. Some other async solution will need to be devised...