Add .00 (toFixed) only if number has less than two decimal places - javascript

I need to add zeroes, so that each number has at least two decimals, but without rounding. So for example:
5 --> 5.00
5.1 --> 5.10
5.11 --> 5.11 (no change)
5.111 --> 5.111 (no change)
5.1111 --> 5.1111 (no change)
My function is missing an IF to check for less than two decimal places:
function addZeroes( num ) {
var num = Number(num);
if ( //idk ) {
num = num.toFixed(2);
}
return num;
}
Thanks!
Posting an alternative answer, in addition to the two below. (Keep in mind that I'm no expert and this is just for text inputs, not for parsing complex values like colors that could have floating point issues, etc.)
function addZeroes( value ) {
//set everything to at least two decimals; removs 3+ zero decimasl, keep non-zero decimals
var new_value = value*1; //removes trailing zeros
new_value = new_value+''; //casts it to string
pos = new_value.indexOf('.');
if (pos==-1) new_value = new_value + '.00';
else {
var integer = new_value.substring(0,pos);
var decimals = new_value.substring(pos+1);
while(decimals.length<2) decimals=decimals+'0';
new_value = integer+'.'+decimals;
}
return new_value;
}
[This is not a duplicate question. The question you linked assumes "knowing that they have at least 1 decimal." Decimal points cannot be assumed in text inputs, and this was making errors.]

Here you go:
function addZeroes(num) {
// Convert input string to a number and store as a variable.
var value = Number(num);
// Split the input string into two arrays containing integers/decimals
var res = num.split(".");
// If there is no decimal point or only one decimal place found.
if(res.length == 1 || res[1].length < 3) {
// Set the number to two decimal places
value = value.toFixed(2);
}
// Return updated or original number.
return value;
}
// If you require the number as a string simply cast back as so
var num = String(value);
See fiddle for demonstration.
edit: Since I first answered this, javascript and I have progressed, here is an improved solution using ES6, but following the same idea:
function addZeroes(num) {
const dec = num.split('.')[1]
const len = dec && dec.length > 2 ? dec.length : 2
return Number(num).toFixed(len)
}
Updated fiddle
edit 2: Or if you are using optional chaining you can do it in one line like so:
const addZeroes = num => Number(num).toFixed(Math.max(num.split('.')[1]?.length, 2) || 2)
Updateder fiddle

Maybe use .toLocaleString():
var num = 5.1;
var numWithZeroes = num.toLocaleString("en",{useGrouping: false,minimumFractionDigits: 2});
console.log(numWithZeroes);
As a function/demo:
function addZeroes(num) {
return num.toLocaleString("en", {useGrouping: false, minimumFractionDigits: 2})
}
console.log('before after correct');
console.log('5 ->', addZeroes(5) , ' --> 5.00');
console.log('5.1 ->', addZeroes(5.1) , ' --> 5.10');
console.log('5.11 ->', addZeroes(5.11) , ' --> 5.11 (no change)');
console.log('5.111 ->', addZeroes(5.111) , ' --> 5.111 (no change)');
console.log('5.1111 ->', addZeroes(5.1111) , '--> 5.1111 (no change)');
console.log('-5 ->', addZeroes(-5) , ' --> -5.00');
And if you must use .toFixed(), here's a one-liner:
var num = 5.1;
var numWithZeroes = num.toFixed(Math.max(((num+'').split(".")[1]||"").length, 2));
console.log(numWithZeroes);
Or, again, as a function/demo:
function addZeroes(num) {
return num.toFixed(Math.max(((num+'').split(".")[1]||"").length, 2));
}
console.log('before after correct');
console.log('5 ->', addZeroes(5) , ' --> 5.00');
console.log('5.1 ->', addZeroes(5.1) , ' --> 5.10');
console.log('5.11 ->', addZeroes(5.11) , ' --> 5.11 (no change)');
console.log('5.111 ->', addZeroes(5.111) , ' --> 5.111 (no change)');
console.log('5.1111 ->', addZeroes(5.1111) , '--> 5.1111 (no change)');
console.log('-5 ->', addZeroes(-5) , ' --> -5.00');

The below code provides one way to do what you want. There are others.
function addZeroes(num) {
// Cast as number
var num = Number(num);
// If not a number, return 0
if (isNaN(num)) {
return 0;
}
// If there is no decimal, or the decimal is less than 2 digits, toFixed
if (String(num).split(".").length < 2 || String(num).split(".")[1].length<=2 ){
num = num.toFixed(2);
}
// Return the number
return num;
}
console.log(addZeroes(5)); // Alerts 5.00
console.log(addZeroes(5.1)); // Alerts 5.10
console.log(addZeroes(5.11)); // Alerts 5.11
console.log(addZeroes(5.111)); // Alerts 5.111
http://jsfiddle.net/nzK4n/

decimalNumber = number => Number.isInteger(number) ? number.toFixed(2) : number

Here is a function that will do this, function expects a number
var addZeroes = function(num) {
var numberAsString = num.toString();
if(numberAsString.indexOf('.') === -1) {
num = num.toFixed(2);
numberAsString = num.toString();
} else if (numberAsString.split(".")[1].length < 3) {
num = num.toFixed(2);
numberAsString = num.toString();
}
return numberAsString
};

For what is worth, this is my recursive solution to this:
const addZeros = (decimal, value, check = true) => {
if (check && decimal <= value.length) return value;
if (decimal <= 0) return value;
const newValue = value.length <= decimal ? '0' + value : value;
return addZeros(decimal - 1, newValue, false);
};
decimal is the number of decimal you want
value is the value you want
check is not suppose to be set, it's here to prevent some issue in the first call.
e.g:
addZeros(3, "3") ==> "003"
addZeros(3, "30") ==> "030"
addZeros(3, "300") ==> "300"
addZeros(3, "3000") ==> "3000"

this solution checks if the number is fixed
decimalNumber = number => Number.isInteger(number) && number % 1 === 0 ? number : number.toFixed(4);

For number type textbox
Append .00 if number present
function addZeroes(ev) {
debugger;
// Convert input string to a number and store as a variable.
var value = Number(ev.value);
// Split the input string into two arrays containing integers/decimals
var res = ev.value.split(".");
// If there is no decimal point or only one decimal place found.
if (res.length == 1 || res[1].length < 3) {
// Set the number to two decimal places
value = value.toFixed(2);
}
// Return updated or original number.
if (ev.value != "") {
ev.value = String(value);
}
}
<input type="number" step=".01" onchange="addZeroes(this)" />

We can solve this using pipe in angular. we will pass digit information parameter to decimal pipe and see how it works -
Digit Info Parameter (3.2-5):
{{ decimal_value | number:'3.2-5' }}
In the above code we are instructing decimal pipe to show atleast 3 integer values before decimal points and minimum 2 fraction digit, maximum 5 fraction digits.
if decimal_value = 5.123 then it will print 005.12300
if decimal_value = 53.1 then it will print 053.10

Work for me -
let a = 12
console.log(a.toLocaleString("en", {useGrouping: false, minimumFractionDigits: 2}))
output - 12.00

Related

in Javascript, exist a function that return only the fractional part of a number, like Math dot something.... ? How can I get it? [duplicate]

I have a floating point number:
var f = 0.1457;
Or:
var f = 4.7005
How do I get just the fraction remainder as integer?
I.e. in the first example I want to get:
var remainder = 1457;
In the second example:
var remainder = 7005;
function frac(f) {
return f % 1;
}
While this is not what most people will want, but TS asked for fract as integer, here it is:
function fract(n){ return Number(String(n).split('.')[1] || 0); }
fract(1.23) // = 23
fract(123) // = 0
fract(0.0008) // = 8
This will do it (up to the 4 digits that you want, change the multipler (10000) to larger or smaller if you want smaller or larger number):
Math.ceil(((f < 1.0) ? f : (f % Math.floor(f))) * 10000)
parseInt(parseFloat(amount).toString().split('.')[1], 10)
You can subtract the floor of the number, giving you just the fractional part, and then multiply by 10000, i.e.:
var remainder = (f-Math.floor(f))*10000;
I would argue that, assuming we want to display these values to the user, treating these numbers as strings would be the best approach. This gets round the issue of fractional values such as 0.002.
I came accross this issue when trying to display prices with the cents in superscript.
let price = 23.43; // 23.43
let strPrice = price.toFixed(2) + ''; // "23.43"
let integer = strPrice.split(".")[0] // "23"
let fractional = strPrice.split(".")[1] // "43"
This also depends on what you want to do with the remainder (as commenters already asked). For instance, if the base number is 1.03, do you want the returned remainder as 3 or 03 -- I mean, do you want it as a number or as a string (for purposes of displaying it to the user). One example would be article price display, where you don't want to conver 03 to 3 (for instance $1.03) where you want to superscript 03.
Next, the problem is with float precision. Consider this:
var price = 1.03;
var frac = (price - Math.floor(price))*100;
// frac = 3.0000000000000027
So you can "solve" this by slicing the string representation without multiplication (and optional zero-padding) in such cases. At the same time, you avoid floating precision issue. Also demonstrated in this jsfiddle.
This post about floating precision might help as well as this one.
var strNumber = f.toString();
var remainder = strNumber.substr(strNumber.indexOf('.') + 1, 4);
remainder = Number(reminder);
Similar method to Martina's answer with a basic modulo operation but solves some of the issues in the comments by returning the same number of decimal places as passed in.
Modifies a method from an answer to a different question on SO which handles the scientific notation for small floats.
Additionally allows the fractional part to be returned as an integer (ie OP's request).
function sfract(n, toInt) {
toInt = false || toInt;
let dec = n.toString().split('e-');
let places = dec.length > 1
? parseInt(dec[1], 10)
: Math.floor(n) !== n ? dec[0].split('.')[1].length : 0;
let fract = parseFloat((n%1).toFixed(places));
return toInt ? fract * Math.pow(10,places) : fract;
};
Tests
function sfract(n, toInt) {
toInt = false || toInt;
let dec = n.toString().split('e-');
let places = dec.length > 1
? parseInt(dec[1], 10)
: Math.floor(n) !== n ? dec[0].split('.')[1].length : 0;
let fract = parseFloat((n%1).toFixed(places));
return toInt ? fract * Math.pow(10,places) : fract;
};
console.log(sfract(0.0000005)); // 5e-7
console.log(sfract(0.0000005, true)); // 5
console.log(sfract(4444)); // 0
console.log(sfract(4444, true)); // 0
console.log(sfract(44444.0000005)); // 5e-7
console.log(sfract(44444.00052121, true)); // 52121
console.log(sfract(34.5697)); // 0.5697
console.log(sfract(730.4583333333321, true)); // 4583333333321
#Udara Seneviratne
const findFraction = (num) => {
return parseInt( // 5.---------------- And finally we parses a "string" type and returns an integer
// 1. We convert our parameter "num" to the "string" type (to work as with an array in the next step)
// result: "1.012312"
num.toString()
// 2. Here we separating the string as an array using the separator: " . "
// result: ["1", "012312"]
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
.split('.')
// 3. With help a method "Array.splice" we cut the first element of our array
// result: ["012312"]
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
.splice(1.1)
// 4. With help a method "Array.shift" we remove the first element from an array and returns that
// result: 012312 (But it's still the "string" type)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
.shift()
)
}
// Try it
console.log("Result is = " + findFraction (1.012312))
// Type of result
console.log("Type of result = " + typeof findFraction (1.012312))
// Some later operation
console.log("Result + some number is = " + findFraction (1.012312) + 555)

Remove zeros after decimal in javascript

If the number after decimals is 0 then remove the zero after decimal else display the number as it is.
Below is the example what I am trying to achieve in vue.
100.023 => 100.023
1230.0 => 1230
This seems to do it:
let s;
// example 1
s = (100.023).toPrecision();
console.log(s === '100.023');
// example 2
s = (1230.0).toPrecision();
console.log(s === '1230');
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision
function removeDecimal(num) {
if (num % 1 !== 0) {
return num;
}
return Math.trunc(num);
}
There are no significant digits in JavaScript so when you have the number 1234.0 it is 1234. If you have a string with "1243.0" convert it to a number and watch the decimal drop off.
console.log(1234.0);
console.log(1234.056);
console.log(+"1234.0");
console.log(+"1234.056");
Also You Can Use the this##
UnitCost = 340.450000000;
NewUnitCost =0;
NewUnitCost =FormatNum(UnitCost, 3);
OutPut:
NewUnitCost = 340.450

Convert a string to a big integer in Javascript?

I am trying to convert a string to a big integer to perform some arithmetic calculations. However, when I try this:
Number("9007199254740993")
...I am getting this unexpected result:
9007199254740992
I suspect that this is probably because of the limit on the size of integers that Number is capable of working with.
Basically, I want to check if two strings are consecutive numbers or not. Since Number is not returning the correct value, I am getting the incorrect difference for "9007199254740993" and "9007199254740992". Specifically, I am expecting 1, but getting 0.
One possibility I considered is dividing each number by a factor to make each of them smaller. Is there any other solution?
Javascript's Number type is a numeric data type in the double-precision 64-bit floating point format (IEEE 754).
If you are dealing with large integers, use a BigInt or a corresponding library.
I you don't want to rely on BigInt and only have positive integers in mind, you can also write the successor test yourself. Full code in the snippet below.
Notes
A string representation of a positive integer is easily convertible to a decimal array where the index represents the exponent to the base 10. For example "42" ~> [2, 4] (since 42 = 2*10^0 + 4*10^1). You can also just as easily convert it back.
Now for the successor test you just need to define the increment operation (which is just adding 1 with carry). With that you can just compare if the increment of one number is equal to the unincremented other number (and vice versa).
Code
// Convert a string representation of positive decimal integer to an array of decimals.
const toArray = numberString => Array.from(numberString, c => parseInt(c))
.reverse();
// Convert the array representation of a positive decimal integer string back to the corresponding string representation (this is the inverse of `toArray`).
const fromArray = numberArray => numberArray.map(String)
.reverse()
.join('');
console.log(fromArray(toArray("9007199254740993")) === "9007199254740993"); // true
// Perform the increment operation on the array representation of the positive decimal integer.
const increment = numberArray => {
let carry = 1;
const incrementedNumberArray = [];
numberArray.forEach(i => {
let j;
if (carry === 0) {
j = i;
} else if (carry === 1) {
if (i === 9) {
j = 0;
} else {
j = i + 1;
carry = 0;
}
}
incrementedNumberArray.push(j);
});
if (carry === 1) {
incrementedNumberArray.push(1);
}
return incrementedNumberArray;
};
console.log(fromArray(increment(toArray("9007199254740993"))) === "9007199254740994"); // true
console.log(fromArray(increment(toArray("9999999999999999"))) === "10000000000000000"); // true
// Test if two strings represent positive integers where one is the other's successor.
const isSuccessor = (a, b) => {
const a_ = increment(toArray(a));
const b_ = increment(toArray(b));
return fromArray(a_) === b || fromArray(b_) === a;
};
console.log(isSuccessor("9007199254740993", "9007199254740994")); // true
console.log(isSuccessor("9007199254740994", "9007199254740993")); // true
console.log(isSuccessor("9999999999999999", "10000000000000000")); // true
console.log(isSuccessor("10000000000000000", "9999999999999999")); // true
console.log(isSuccessor("10000000000000000", "10000000000000002")); // false
You can use BIG integer library like one in JAVA.
check here
npm install big-integer
var bigInt = require("big-integer");
var largeNumber1 = bigInt("9007199254740993");
var largeNumber2 = bigInt("9007199254740994"); // any other number
var ans = largeNumber1.minus(largeNumber2);
if(ans == 1 || ans == -1){
console.log('consecutive ')
}else{
console.log('not consecutive ')
}
Note: I recommend you to use BigInt(as suggested by #Andreas in comment), if you are dealing with Big Numbers.
UPDATED
Use this code to compare big positive integers(The arguments should be in string format)
function compareBigNumber(num1, num2) {
if (num1 > Number.MAX_SAFE_INTEGER && num2 > Number.MAX_SAFE_INTEGER) {
var newNum1 = num1.split('').reverse();
var newNum2 = num2.split('').reverse();
do {
newNum1.pop();
newNum2.pop();
} while (newNum1[newNum1.length-1] === '0' || newNum2[newNum2.length-1] === '0')
return compareBigNumber(newNum1.reverse().join(''), newNum2.reverse().join(''));
} else if(num1 > Number.MAX_SAFE_INTEGER){
return 'num1 is greater'
} else if (num2 > Number.MAX_SAFE_INTEGER) {
return 'num2 is greater'
}
else {
var num1Int = parseInt(num1);
var num2Int = parseInt(num2);
if (num1Int > num2Int) {
return 'Num1 is greater';
} else if (num2Int > num1Int){
return 'Num2 is greater'
} else {
return 'Num1 is equal to Num2';
}
}
}
console.log(compareBigNumber("9007199254740992", "9007199254740993"))
console.log(compareBigNumber("100000000000000000000", "0"))

Check if a number has a decimal place/is a whole number

I am looking for an easy way in JavaScript to check if a number has a decimal place in it (in order to determine if it is an integer). For instance,
23 -> OK
5 -> OK
3.5 -> not OK
34.345 -> not OK
if(number is integer) {...}
Using modulus will work:
num % 1 != 0
// 23 % 1 = 0
// 23.5 % 1 = 0.5
Note that this is based on the numerical value of the number, regardless of format. It treats numerical strings containing whole numbers with a fixed decimal point the same as integers:
'10.0' % 1; // returns 0
10 % 1; // returns 0
'10.5' % 1; // returns 0.5
10.5 % 1; // returns 0.5
Number.isInteger(23); // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false:
Number.isInteger() is part of the ES6 standard and not supported in IE11.
It returns false for NaN, Infinity and non-numeric arguments while x % 1 != 0 returns true.
Or you could just use this to find out if it is NOT a decimal:
string.indexOf(".") == -1;
Simple, but effective!
Math.floor(number) === number;
The most common solution is to strip the integer portion of the number and compare it to zero like so:
function Test()
{
var startVal = 123.456
alert( (startVal - Math.floor(startVal)) != 0 )
}
Number.isSafeInteger(value);
In JavaScript, isSafeInteger() is a Number method that is used to return a Boolean value indicating whether a value is a safe integer. This means that it is an integer value that can be exactly represented as an IEEE-754 double precision number without rounding.
//How about byte-ing it?
Number.prototype.isInt= function(){
return this== this>> 0;
}
I always feel kind of bad for bit operators in javascript-
they hardly get any exercise.
Number.isInteger() is probably the most concise. It returns true if it is an integer, and false if it isn't.
number = 20.5
if (number == Math.floor(number)) {
alert("Integer")
} else {
alert("Decimal")
}
Pretty cool and works for things like XX.0 too!
It works because Math.floor() chops off any decimal if it has one so if the floor is different from the original number we know it is a decimal! And no string conversions :)
var re=/^-?[0-9]+$/;
var num=10;
re.test(num);
convert number string to array, split by decimal point. Then, if the array has only one value, that means no decimal in string.
if(!number.split(".")[1]){
//do stuff
}
This way you can also know what the integer and decimal actually are. a more advanced example would be.
number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1];
if(!dece){
//do stuff
}
function isDecimal(n){
if(n == "")
return false;
var strCheck = "0123456789";
var i;
for(i in n){
if(strCheck.indexOf(n[i]) == -1)
return false;
}
return true;
}
parseInt(num) === num
when passed a number, parseInt() just returns the number as int:
parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3 // true
Use following if value is string (e.g. from <input):
Math.floor(value).toString() !== value
I add .toString() to floor to make it work also for cases when value == "1." (ends with decimal separator or another string). Also Math.floor always returns some value so .toString() never fails.
Here's an excerpt from my guard library (inspired by Effective JavaScript by David Herman):
var guard = {
guard: function(x) {
if (!this.test(x)) {
throw new TypeError("expected " + this);
}
}
// ...
};
// ...
var number = Object.create(guard);
number.test = function(x) {
return typeof x === "number" || x instanceof Number;
};
number.toString = function() {
return "number";
};
var uint32 = Object.create(guard);
uint32.test = function(x) {
return typeof x === "number" && x === (x >>> 0);
};
uint32.toString = function() {
return "uint32";
};
var decimal = Object.create(guard);
decimal.test = function(x) {
return number.test(x) && !uint32.test(x);
};
decimal.toString = function() {
return "decimal";
};
uint32.guard(1234); // fine
uint32.guard(123.4); // TypeError: expected uint32
decimal.guard(1234); // TypeError: expected decimal
decimal.guard(123.4); // fine
You can multiply it by 10 and then do a "modulo" operation/divison with 10, and check if result of that two operations is zero. Result of that two operations will give you first digit after the decimal point.
If result is equal to zero then the number is a whole number.
if ( (int)(number * 10.0) % 10 == 0 ){
// your code
}
function isDecimal(num) {
return (num !== parseInt(num, 10));
}
You can use the bitwise operations that do not change the value (^ 0 or ~~) to discard the decimal part, which can be used for rounding. After rounding the number, it is compared to the original value:
function isDecimal(num) {
return (num ^ 0) !== num;
}
console.log( isDecimal(1) ); // false
console.log( isDecimal(1.5) ); // true
console.log( isDecimal(-0.5) ); // true
function isWholeNumber(num) {
return num === Math.round(num);
}
When using counters with decimal steps, checking if number is round will actually fail, as shown below. So it might be safest (although slow) to format the number with 9 (could be more) decimal places, and if it ends with 9 zeros, then it's a whole number.
const isRound = number => number.toFixed(9).endsWith('000000000');
for (let counter = 0; counter < 2; counter += 0.1) {
console.log({ counter, modulo: counter % 1, formatted: counter.toFixed(9), isRound: isRound(counter) });
}
Perhaps this works for you?
It uses regex to check if there is a comma in the number, and if there is not, then it will add the comma and stripe.
var myNumber = '50';
function addCommaStripe(text){
if(/,/.test(text) == false){
return text += ',-';
} else {
return text;
}
}
myNumber = addCommaStripe(myNumber);
You can use this:
bool IsInteger() {
if (num.indexOf(".") != -1) // a decimal
{
return Math.ceil(num) == Math.floor(num); // passes for 1.0 as integer if thats the intent.
}
return Number.isSafeInteger(num);
}
to check if the number is integer or decimal.
Using Number.isInteger(num) can help check what would count as whole number and what would not.
For example:
let num1 = 6.0000000000000001; // 16 decimal places
let num2 = 6.000000000000001; // 15 decimal places
Number.isInteger(num1); // true, because of loss of precision
// while:
Number.isInteger(num2); // false
So, in my opinion it's safe to use Number.isInteger() over other suggested ways if what you need is to know what is an integer mathematically.
Function for check number is Decimal or whole number
function IsDecimalExist(p_decimalNumber) {
var l_boolIsExist = true;
if (p_decimalNumber % 1 == 0)
l_boolIsExist = false;
return l_boolIsExist;
}

How to convert decimal to hexadecimal in JavaScript

How do you convert decimal values to their hexadecimal equivalent in JavaScript?
Convert a number to a hexadecimal string with:
hexString = yourNumber.toString(16);
And reverse the process with:
yourNumber = parseInt(hexString, 16);
If you need to handle things like bit fields or 32-bit colors, then you need to deal with signed numbers. The JavaScript function toString(16) will return a negative hexadecimal number which is usually not what you want. This function does some crazy addition to make it a positive number.
function decimalToHexString(number)
{
if (number < 0)
{
number = 0xFFFFFFFF + number + 1;
}
return number.toString(16).toUpperCase();
}
console.log(decimalToHexString(27));
console.log(decimalToHexString(48.6));
The code below will convert the decimal value d to hexadecimal. It also allows you to add padding to the hexadecimal result. So 0 will become 00 by default.
function decimalToHex(d, padding) {
var hex = Number(d).toString(16);
padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;
while (hex.length < padding) {
hex = "0" + hex;
}
return hex;
}
function toHex(d) {
return ("0"+(Number(d).toString(16))).slice(-2).toUpperCase()
}
For completeness, if you want the two's-complement hexadecimal representation of a negative number, you can use the zero-fill-right shift >>> operator. For instance:
> (-1).toString(16)
"-1"
> ((-2)>>>0).toString(16)
"fffffffe"
There is however one limitation: JavaScript bitwise operators treat their operands as a sequence of 32 bits, that is, you get the 32-bits two's complement.
With padding:
function dec2hex(i) {
return (i+0x10000).toString(16).substr(-4).toUpperCase();
}
The accepted answer did not take into account single digit returned hexadecimal codes. This is easily adjusted by:
function numHex(s)
{
var a = s.toString(16);
if ((a.length % 2) > 0) {
a = "0" + a;
}
return a;
}
and
function strHex(s)
{
var a = "";
for (var i=0; i<s.length; i++) {
a = a + numHex(s.charCodeAt(i));
}
return a;
}
I believe the above answers have been posted numerous times by others in one form or another. I wrap these in a toHex() function like so:
function toHex(s)
{
var re = new RegExp(/^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/);
if (re.test(s)) {
return '#' + strHex( s.toString());
}
else {
return 'A' + strHex(s);
}
}
Note that the numeric regular expression came from 10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency.
Update: After testing this thing several times I found an error (double quotes in the RegExp), so I fixed that. HOWEVER! After quite a bit of testing and having read the post by almaz - I realized I could not get negative numbers to work.
Further - I did some reading up on this and since all JavaScript numbers are stored as 64 bit words no matter what - I tried modifying the numHex code to get the 64 bit word. But it turns out you can not do that. If you put "3.14159265" AS A NUMBER into a variable - all you will be able to get is the "3", because the fractional portion is only accessible by multiplying the number by ten(IE:10.0) repeatedly. Or to put that another way - the hexadecimal value of 0xF causes the floating point value to be translated into an integer before it is ANDed which removes everything behind the period. Rather than taking the value as a whole (i.e.: 3.14159265) and ANDing the floating point value against the 0xF value.
So the best thing to do, in this case, is to convert the 3.14159265 into a string and then just convert the string. Because of the above, it also makes it easy to convert negative numbers because the minus sign just becomes 0x26 on the front of the value.
So what I did was on determining that the variable contains a number - just convert it to a string and convert the string. This means to everyone that on the server side you will need to unhex the incoming string and then to determine the incoming information is numeric. You can do that easily by just adding a "#" to the front of numbers and "A" to the front of a character string coming back. See the toHex() function.
Have fun!
After another year and a lot of thinking, I decided that the "toHex" function (and I also have a "fromHex" function) really needed to be revamped. The whole question was "How can I do this more efficiently?" I decided that a to/from hexadecimal function should not care if something is a fractional part but at the same time it should ensure that fractional parts are included in the string.
So then the question became, "How do you know you are working with a hexadecimal string?". The answer is simple. Use the standard pre-string information that is already recognized around the world.
In other words - use "0x". So now my toHex function looks to see if that is already there and if it is - it just returns the string that was sent to it. Otherwise, it converts the string, number, whatever. Here is the revised toHex function:
/////////////////////////////////////////////////////////////////////////////
// toHex(). Convert an ASCII string to hexadecimal.
/////////////////////////////////////////////////////////////////////////////
toHex(s)
{
if (s.substr(0,2).toLowerCase() == "0x") {
return s;
}
var l = "0123456789ABCDEF";
var o = "";
if (typeof s != "string") {
s = s.toString();
}
for (var i=0; i<s.length; i++) {
var c = s.charCodeAt(i);
o = o + l.substr((c>>4),1) + l.substr((c & 0x0f),1);
}
return "0x" + o;
}
This is a very fast function that takes into account single digits, floating point numbers, and even checks to see if the person is sending a hex value over to be hexed again. It only uses four function calls and only two of those are in the loop. To un-hex the values you use:
/////////////////////////////////////////////////////////////////////////////
// fromHex(). Convert a hex string to ASCII text.
/////////////////////////////////////////////////////////////////////////////
fromHex(s)
{
var start = 0;
var o = "";
if (s.substr(0,2).toLowerCase() == "0x") {
start = 2;
}
if (typeof s != "string") {
s = s.toString();
}
for (var i=start; i<s.length; i+=2) {
var c = s.substr(i, 2);
o = o + String.fromCharCode(parseInt(c, 16));
}
return o;
}
Like the toHex() function, the fromHex() function first looks for the "0x" and then it translates the incoming information into a string if it isn't already a string. I don't know how it wouldn't be a string - but just in case - I check. The function then goes through, grabbing two characters and translating those in to ASCII characters. If you want it to translate Unicode, you will need to change the loop to going by four(4) characters at a time. But then you also need to ensure that the string is NOT divisible by four. If it is - then it is a standard hexadecimal string. (Remember the string has "0x" on the front of it.)
A simple test script to show that -3.14159265, when converted to a string, is still -3.14159265.
<?php
echo <<<EOD
<html>
<head><title>Test</title>
<script>
var a = -3.14159265;
alert( "A = " + a );
var b = a.toString();
alert( "B = " + b );
</script>
</head>
<body>
</body>
</html>
EOD;
?>
Because of how JavaScript works in respect to the toString() function, all of those problems can be eliminated which before were causing problems. Now all strings and numbers can be converted easily. Further, such things as objects will cause an error to be generated by JavaScript itself. I believe this is about as good as it gets. The only improvement left is for W3C to just include a toHex() and fromHex() function in JavaScript.
Without the loop:
function decimalToHex(d) {
var hex = Number(d).toString(16);
hex = "000000".substr(0, 6 - hex.length) + hex;
return hex;
}
// Or "#000000".substr(0, 7 - hex.length) + hex;
// Or whatever
// *Thanks to MSDN
Also isn't it better not to use loop tests that have to be evaluated?
For example, instead of:
for (var i = 0; i < hex.length; i++){}
have
for (var i = 0, var j = hex.length; i < j; i++){}
Combining some of these good ideas for an RGB-value-to-hexadecimal function (add the # elsewhere for HTML/CSS):
function rgb2hex(r,g,b) {
if (g !== undefined)
return Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);
else
return Number(0x1000000 + r[0]*0x10000 + r[1]*0x100 + r[2]).toString(16).substring(1);
}
Constrained/padded to a set number of characters:
function decimalToHex(decimal, chars) {
return (decimal + Math.pow(16, chars)).toString(16).slice(-chars).toUpperCase();
}
For anyone interested, here's a JSFiddle comparing most of the answers given to this question.
And here's the method I ended up going with:
function decToHex(dec) {
return (dec + Math.pow(16, 6)).toString(16).substr(-6)
}
Also, bear in mind that if you're looking to convert from decimal to hex for use in CSS as a color data type, you might instead prefer to extract the RGB values from the decimal and use rgb().
For example (JSFiddle):
let c = 4210330 // your color in decimal format
let rgb = [(c & 0xff0000) >> 16, (c & 0x00ff00) >> 8, (c & 0x0000ff)]
// Vanilla JS:
document.getElementById('some-element').style.color = 'rgb(' + rgb + ')'
// jQuery:
$('#some-element').css('color', 'rgb(' + rgb + ')')
This sets #some-element's CSS color property to rgb(64, 62, 154).
var number = 3200;
var hexString = number.toString(16);
The 16 is the radix and there are 16 values in a hexadecimal number :-)
function dec2hex(i)
{
var result = "0000";
if (i >= 0 && i <= 15) { result = "000" + i.toString(16); }
else if (i >= 16 && i <= 255) { result = "00" + i.toString(16); }
else if (i >= 256 && i <= 4095) { result = "0" + i.toString(16); }
else if (i >= 4096 && i <= 65535) { result = i.toString(16); }
return result
}
If you want to convert a number to a hexadecimal representation of an RGBA color value, I've found this to be the most useful combination of several tips from here:
function toHexString(n) {
if(n < 0) {
n = 0xFFFFFFFF + n + 1;
}
return "0x" + ("00000000" + n.toString(16).toUpperCase()).substr(-8);
}
AFAIK comment 57807 is wrong and should be something like:
var hex = Number(d).toString(16);
instead of
var hex = parseInt(d, 16);
function decimalToHex(d, padding) {
var hex = Number(d).toString(16);
padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;
while (hex.length < padding) {
hex = "0" + hex;
}
return hex;
}
And if the number is negative?
Here is my version.
function hexdec (hex_string) {
hex_string=((hex_string.charAt(1)!='X' && hex_string.charAt(1)!='x')?hex_string='0X'+hex_string : hex_string);
hex_string=(hex_string.charAt(2)<8 ? hex_string =hex_string-0x00000000 : hex_string=hex_string-0xFFFFFFFF-1);
return parseInt(hex_string, 10);
}
As the accepted answer states, the easiest way to convert from decimal to hexadecimal is var hex = dec.toString(16). However, you may prefer to add a string conversion, as it ensures that string representations like "12".toString(16) work correctly.
// Avoids a hard-to-track-down bug by returning `c` instead of `12`
(+"12").toString(16);
To reverse the process you may also use the solution below, as it is even shorter.
var dec = +("0x" + hex);
It seems to be slower in Google Chrome and Firefox, but is significantly faster in Opera. See http://jsperf.com/hex-to-dec.
I'm doing conversion to hex string in a pretty large loop, so I tried several techniques in order to find the fastest one. My requirements were to have a fixed-length string as a result, and encode negative values properly (-1 => ff..f).
Simple .toString(16) didn't work for me since I needed negative values to be properly encoded. The following code is the quickest I've tested so far on 1-2 byte values (note that symbols defines the number of output symbols you want to get, that is for 4-byte integer it should be equal to 8):
var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function getHexRepresentation(num, symbols) {
var result = '';
while (symbols--) {
result = hex[num & 0xF] + result;
num >>= 4;
}
return result;
}
It performs faster than .toString(16) on 1-2 byte numbers and slower on larger numbers (when symbols >= 6), but still should outperform methods that encode negative values properly.
Converting hex color numbers to hex color strings:
A simple solution with toString and ES6 padStart for converting hex color numbers to hex color strings.
const string = `#${color.toString(16).padStart(6, '0')}`;
For example:
0x000000 will become #000000
0xFFFFFF will become #FFFFFF
Check this example in a fiddle here
How to convert decimal to hexadecimal in JavaScript
I wasn't able to find a brutally clean/simple decimal to hexadecimal conversion that didn't involve a mess of functions and arrays ... so I had to make this for myself.
function DecToHex(decimal) { // Data (decimal)
length = -1; // Base string length
string = ''; // Source 'string'
characters = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]; // character array
do { // Grab each nibble in reverse order because JavaScript has no unsigned left shift
string += characters[decimal & 0xF]; // Mask byte, get that character
++length; // Increment to length of string
} while (decimal >>>= 4); // For next character shift right 4 bits, or break on 0
decimal += 'x'; // Convert that 0 into a hex prefix string -> '0x'
do
decimal += string[length];
while (length--); // Flip string forwards, with the prefixed '0x'
return (decimal); // return (hexadecimal);
}
/* Original: */
D = 3678; // Data (decimal)
C = 0xF; // Check
A = D; // Accumulate
B = -1; // Base string length
S = ''; // Source 'string'
H = '0x'; // Destination 'string'
do {
++B;
A& = C;
switch(A) {
case 0xA: A='A'
break;
case 0xB: A='B'
break;
case 0xC: A='C'
break;
case 0xD: A='D'
break;
case 0xE: A='E'
break;
case 0xF: A='F'
break;
A = (A);
}
S += A;
D >>>= 0x04;
A = D;
} while(D)
do
H += S[B];
while (B--)
S = B = A = C = D; // Zero out variables
alert(H); // H: holds hexadecimal equivalent
You can do something like this in ECMAScript 6:
const toHex = num => (num).toString(16).toUpperCase();
If you are looking for converting Large integers i.e. Numbers greater than Number.MAX_SAFE_INTEGER -- 9007199254740991, then you can use the following code
const hugeNumber = "9007199254740991873839" // Make sure its in String
const hexOfHugeNumber = BigInt(hugeNumber).toString(16);
console.log(hexOfHugeNumber)
To sum it all up;
function toHex(i, pad) {
if (typeof(pad) === 'undefined' || pad === null) {
pad = 2;
}
var strToParse = i.toString(16);
while (strToParse.length < pad) {
strToParse = "0" + strToParse;
}
var finalVal = parseInt(strToParse, 16);
if ( finalVal < 0 ) {
finalVal = 0xFFFFFFFF + finalVal + 1;
}
return finalVal;
}
However, if you don't need to convert it back to an integer at the end (i.e. for colors), then just making sure the values aren't negative should suffice.
I haven't found a clear answer, without checks if it is negative or positive, that uses two's complement (negative numbers included). For that, I show my solution to one byte:
((0xFF + number +1) & 0x0FF).toString(16);
You can use this instruction to any number bytes, only you add FF in respective places. For example, to two bytes:
((0xFFFF + number +1) & 0x0FFFF).toString(16);
If you want cast an array integer to string hexadecimal:
s = "";
for(var i = 0; i < arrayNumber.length; ++i) {
s += ((0xFF + arrayNumber[i] +1) & 0x0FF).toString(16);
}
In case you're looking to convert to a 'full' JavaScript or CSS representation, you can use something like:
numToHex = function(num) {
var r=((0xff0000&num)>>16).toString(16),
g=((0x00ff00&num)>>8).toString(16),
b=(0x0000ff&num).toString(16);
if (r.length==1) { r = '0'+r; }
if (g.length==1) { g = '0'+g; }
if (b.length==1) { b = '0'+b; }
return '0x'+r+g+b; // ('#' instead of'0x' for CSS)
};
var dec = 5974678;
console.log( numToHex(dec) ); // 0x5b2a96
This is based on Prestaul and Tod's solutions. However, this is a generalisation that accounts for varying size of a variable (e.g. Parsing signed value from a microcontroller serial log).
function decimalToPaddedHexString(number, bitsize)
{
let byteCount = Math.ceil(bitsize/8);
let maxBinValue = Math.pow(2, bitsize)-1;
/* In node.js this function fails for bitsize above 32bits */
if (bitsize > 32)
throw "number above maximum value";
/* Conversion to unsigned form based on */
if (number < 0)
number = maxBinValue + number + 1;
return "0x"+(number >>> 0).toString(16).toUpperCase().padStart(byteCount*2, '0');
}
Test script:
for (let n = 0 ; n < 64 ; n++ ) {
let s=decimalToPaddedHexString(-1, n);
console.log(`decimalToPaddedHexString(-1,${(n+"").padStart(2)}) = ${s.padStart(10)} = ${("0b"+parseInt(s).toString(2)).padStart(34)}`);
}
Test results:
decimalToPaddedHexString(-1, 0) = 0x0 = 0b0
decimalToPaddedHexString(-1, 1) = 0x01 = 0b1
decimalToPaddedHexString(-1, 2) = 0x03 = 0b11
decimalToPaddedHexString(-1, 3) = 0x07 = 0b111
decimalToPaddedHexString(-1, 4) = 0x0F = 0b1111
decimalToPaddedHexString(-1, 5) = 0x1F = 0b11111
decimalToPaddedHexString(-1, 6) = 0x3F = 0b111111
decimalToPaddedHexString(-1, 7) = 0x7F = 0b1111111
decimalToPaddedHexString(-1, 8) = 0xFF = 0b11111111
decimalToPaddedHexString(-1, 9) = 0x01FF = 0b111111111
decimalToPaddedHexString(-1,10) = 0x03FF = 0b1111111111
decimalToPaddedHexString(-1,11) = 0x07FF = 0b11111111111
decimalToPaddedHexString(-1,12) = 0x0FFF = 0b111111111111
decimalToPaddedHexString(-1,13) = 0x1FFF = 0b1111111111111
decimalToPaddedHexString(-1,14) = 0x3FFF = 0b11111111111111
decimalToPaddedHexString(-1,15) = 0x7FFF = 0b111111111111111
decimalToPaddedHexString(-1,16) = 0xFFFF = 0b1111111111111111
decimalToPaddedHexString(-1,17) = 0x01FFFF = 0b11111111111111111
decimalToPaddedHexString(-1,18) = 0x03FFFF = 0b111111111111111111
decimalToPaddedHexString(-1,19) = 0x07FFFF = 0b1111111111111111111
decimalToPaddedHexString(-1,20) = 0x0FFFFF = 0b11111111111111111111
decimalToPaddedHexString(-1,21) = 0x1FFFFF = 0b111111111111111111111
decimalToPaddedHexString(-1,22) = 0x3FFFFF = 0b1111111111111111111111
decimalToPaddedHexString(-1,23) = 0x7FFFFF = 0b11111111111111111111111
decimalToPaddedHexString(-1,24) = 0xFFFFFF = 0b111111111111111111111111
decimalToPaddedHexString(-1,25) = 0x01FFFFFF = 0b1111111111111111111111111
decimalToPaddedHexString(-1,26) = 0x03FFFFFF = 0b11111111111111111111111111
decimalToPaddedHexString(-1,27) = 0x07FFFFFF = 0b111111111111111111111111111
decimalToPaddedHexString(-1,28) = 0x0FFFFFFF = 0b1111111111111111111111111111
decimalToPaddedHexString(-1,29) = 0x1FFFFFFF = 0b11111111111111111111111111111
decimalToPaddedHexString(-1,30) = 0x3FFFFFFF = 0b111111111111111111111111111111
decimalToPaddedHexString(-1,31) = 0x7FFFFFFF = 0b1111111111111111111111111111111
decimalToPaddedHexString(-1,32) = 0xFFFFFFFF = 0b11111111111111111111111111111111
Thrown: 'number above maximum value'
Note: Not too sure why it fails above 32 bitsize
rgb(255, 255, 255) // returns FFFFFF
rgb(255, 255, 300) // returns FFFFFF
rgb(0,0,0) // returns 000000
rgb(148, 0, 211) // returns 9400D3
function rgb(...values){
return values.reduce((acc, cur) => {
let val = cur >= 255 ? 'ff' : cur <= 0 ? '00' : Number(cur).toString(16);
return acc + (val.length === 1 ? '0'+val : val);
}, '').toUpperCase();
}
Arbitrary precision
This solution take on input decimal string, and return hex string. A decimal fractions are supported. Algorithm
split number to sign (s), integer part (i) and fractional part (f) e.g for -123.75 we have s=true, i=123, f=75
integer part to hex:
if i='0' stop
get modulo: m=i%16 (in arbitrary precision)
convert m to hex digit and put to result string
for next step calc integer part i=i/16 (in arbitrary precision)
fractional part
count fractional digits n
multiply k=f*16 (in arbitrary precision)
split k to right part with n digits and put them to f, and left part with rest of digits and put them to d
convert d to hex and add to result.
finish when number of result fractional digits is enough
// #param decStr - string with non-negative integer
// #param divisor - positive integer
function dec2HexArbitrary(decStr, fracDigits=0) {
// Helper: divide arbitrary precision number by js number
// #param decStr - string with non-negative integer
// #param divisor - positive integer
function arbDivision(decStr, divisor)
{
// algorithm https://www.geeksforgeeks.org/divide-large-number-represented-string/
let ans='';
let idx = 0;
let temp = +decStr[idx];
while (temp < divisor) temp = temp * 10 + +decStr[++idx];
while (decStr.length > idx) {
ans += (temp / divisor)|0 ;
temp = (temp % divisor) * 10 + +decStr[++idx];
}
if (ans.length == 0) return "0";
return ans;
}
// Helper: calc module of arbitrary precision number
// #param decStr - string with non-negative integer
// #param mod - positive integer
function arbMod(decStr, mod) {
// algorithm https://www.geeksforgeeks.org/how-to-compute-mod-of-a-big-number/
let res = 0;
for (let i = 0; i < decStr.length; i++)
res = (res * 10 + +decStr[i]) % mod;
return res;
}
// Helper: multiply arbitrary precision integer by js number
// #param decStr - string with non-negative integer
// #param mult - positive integer
function arbMultiply(decStr, mult) {
let r='';
let m=0;
for (let i = decStr.length-1; i >=0 ; i--) {
let n = m+mult*(+decStr[i]);
r= (i ? n%10 : n) + r
m= n/10|0;
}
return r;
}
// dec2hex algorithm starts here
let h= '0123456789abcdef'; // hex 'alphabet'
let m= decStr.match(/-?(.*?)\.(.*)?/) || decStr.match(/-?(.*)/); // separate sign,integer,ractional
let i= m[1].replace(/^0+/,'').replace(/^$/,'0'); // integer part (without sign and leading zeros)
let f= (m[2]||'0').replace(/0+$/,'').replace(/^$/,'0'); // fractional part (without last zeros)
let s= decStr[0]=='-'; // sign
let r=''; // result
if(i=='0') r='0';
while(i!='0') { // integer part
r=h[arbMod(i,16)]+r;
i=arbDivision(i,16);
}
if(fracDigits) r+=".";
let n = f.length;
for(let j=0; j<fracDigits; j++) { // frac part
let k= arbMultiply(f,16);
f = k.slice(-n);
let d= k.slice(0,k.length-n);
r+= d.length ? h[+d] : '0';
}
return (s?'-':'')+r;
}
// -----------
// TESTS
// -----------
let tests = [
["0",2],
["000",2],
["123",0],
["-123",0],
["00.000",2],
["255.75",5],
["-255.75",5],
["127.999",32],
];
console.log('Input Standard Abitrary');
tests.forEach(t=> {
let nonArb = (+t[0]).toString(16).padEnd(17,' ');
let arb = dec2HexArbitrary(t[0],t[1]);
console.log(t[0].padEnd(10,' '), nonArb, arb);
});
// Long Example (40 digits after dot)
let example = "123456789012345678901234567890.09876543210987654321"
console.log(`\nLong Example:`);
console.log('dec:',example);
console.log('hex: ',dec2HexArbitrary(example,40));
The problem basically how many padding zeros to expect.
If you expect string 01 and 11 from Number 1 and 17. it's better to use Buffer as a bridge, with which number is turn into bytes, and then the hex is just an output format of it. And the bytes organization is well controlled by Buffer functions, like writeUInt32BE, writeInt16LE, etc.
import { Buffer } from 'buffer';
function toHex(n) { // 4byte
const buff = Buffer.alloc(4);
buff.writeInt32BE(n);
return buff.toString('hex');
}
> toHex(1)
'00000001'
> toHex(17)
'00000011'
> toHex(-1)
'ffffffff'
> toHex(-1212)
'fffffb44'
> toHex(1212)
'000004bc'
Here's my solution:
hex = function(number) {
return '0x' + Math.abs(number).toString(16);
}
The question says: "How to convert decimal to hexadecimal in JavaScript". While, the question does not specify that the hexadecimal string should begin with a 0x prefix, anybody who writes code should know that 0x is added to hexadecimal codes to distinguish hexadecimal codes from programmatic identifiers and other numbers (1234 could be hexadecimal, decimal, or even octal).
Therefore, to correctly answer this question, for the purpose of script-writing, you must add the 0x prefix.
The Math.abs(N) function converts negatives to positives, and as a bonus, it doesn't look like somebody ran it through a wood-chipper.
The answer I wanted, would have had a field-width specifier, so we could for example show 8/16/32/64-bit values the way you would see them listed in a hexadecimal editing application. That, is the actual, correct answer.

Categories