Skip to content

Instantly share code, notes, and snippets.

@ghalimi
Last active March 22, 2022 01:22
Show Gist options
  • Save ghalimi/4484872 to your computer and use it in GitHub Desktop.
Save ghalimi/4484872 to your computer and use it in GitHub Desktop.
DEC2HEX Function
// Copyright (c) 2012 Sutoiku, Inc. (MIT License)
function DEC2HEX(number, places) {
// Return error if number is not a number
if (isNaN(number)) return '#VALUE!';
// Return error if number is not decimal, is lower than -549755813888, or is greater than 549755813887
if (!/^-?[0-9]{1,12}$/.test(number) || number < -549755813888 || number > 549755813887) return '#NUM!';
// Ignore places and return a 10-character hexadecimal number if number is negative
if (number < 0) {
return (1099511627776 + number).toString(16);
}
// Convert decimal number to hexadecimal
var result = parseInt(number, 10).toString(16);
// Return hexadecimal number using the minimum number of characters necessary if places is undefined
if (typeof places === 'undefined') {
return result;
} else {
// Return error if places is nonnumeric
if (isNaN(places)) return '#VALUE!';
// Return error if places is negative
if (places < 0) return '#NUM!';
// Truncate places in case it is not an integer
places = Math.floor(places);
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string)
return (places >= result.length) ? _s.repeat('0', places - result.length) + result : '#NUM!';
}
}
@torontocaper
Copy link

incredible. thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment