How do I zero-fill a number? - javascript

I have a working decimal to binary converter, but I want it to ALWAYS show 8 digits,
so if I put in 3 it will say '00000011' and not '11'
Anyone a clue how this can be done?
my code:
<script type="text/javascript">
function ConvertToBinary(dec) {
var bits = [];
var dividend = dec;
var remainder = 0;
while (dividend >= 2) {
remainder = dividend % 2;
bits.push(remainder);
dividend = (dividend - remainder) / 2;
}
bits.push(dividend);
bits.reverse();
return bits.join("");
}
<input type="text" id="txtDec" maxlength="3"/>
<input type="button" value="Convert" onclick="document.getElementById('spBin').innerHTML=ConvertToBinary(document.getElementById('txtDec').value);" />
<span id="spBin"></span>

JavaScript already makes the conversion for you, from a number, using toString method, because you can specify the radix (see the link above):
var n = 13;
console.log(n.toString(2)) // "1101"
If you want add lead zero, in case less then 8, you could have:
var bits = n.toString(2);
console.log("00000000".substr(bits.length) + bits);
With just one method call.
Edit: this answer was written in 2013, nowadays the method padStart can be used instead for the padding:
console.log(n.toString(2).padStart(8, "0"));

How about this:
return String('000000000' + bits.join("")).slice(-8);
Demo (change "dividend" to try with different numbers)
Basically adds 8 zeros to the left and then removes anything more than 8 characters long from the left.

How about before bits.reverse(); You do a while loop like this:
while(bits.length < 8){
bits.push(0);
}

Here's an example solution that will left-pad a number with zeros
#param "num" the number to be left-padded with zeros
#param "width" the number of characters required as a result
#return String the left-padded number
function zeroFill(num, width) {
str = String((new Array(width+1)).join('0') + num).slice(-width)
return str
}
There are other solutions which use a loop to create the zeros.

Related

How to display a NUMBER (not string) to have always 2 digits in Javascript [duplicate]

I would like to format my numbers to always display 2 decimal places, rounding where applicable.
Examples:
number display
------ -------
1 1.00
1.341 1.34
1.345 1.35
I have been using this:
parseFloat(num).toFixed(2);
But it's displaying 1 as 1, rather than 1.00.
(Math.round(num * 100) / 100).toFixed(2);
Live Demo
var num1 = "1";
document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2);
var num2 = "1.341";
document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);
var num3 = "1.345";
document.getElementById('num3').innerHTML = (Math.round(num3 * 100) / 100).toFixed(2);
span {
border: 1px solid #000;
margin: 5px;
padding: 5px;
}
<span id="num1"></span>
<span id="num2"></span>
<span id="num3"></span>
Note that it will round to 2 decimal places, so the input 1.346 will return 1.35.
Number(1).toFixed(2); // 1.00
Number(1.341).toFixed(2); // 1.34
Number(1.345).toFixed(2); // 1.34 NOTE: See andy's comment below.
Number(1.3450001).toFixed(2); // 1.35
document.getElementById('line1').innerHTML = Number(1).toFixed(2);
document.getElementById('line2').innerHTML = Number(1.341).toFixed(2);
document.getElementById('line3').innerHTML = Number(1.345).toFixed(2);
document.getElementById('line4').innerHTML = Number(1.3450001).toFixed(2);
<span id="line1"></span>
<br/>
<span id="line2"></span>
<br/>
<span id="line3"></span>
<br/>
<span id="line4"></span>
This answer will fail if value = 1.005.
As a better solution, the rounding problem can be avoided by using numbers represented in exponential notation:
Number(Math.round(1.005+'e2')+'e-2'); // 1.01
Cleaner code as suggested by #Kon, and the original author:
Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces)
You may add toFixed() at the end to retain the decimal point e.g: 1.00 but note that it will return as string.
Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces).toFixed(decimalPlaces)
Credit: Rounding Decimals in JavaScript
For modern browsers, use toLocaleString:
var num = 1.345;
num.toLocaleString(undefined, { maximumFractionDigits: 2, minimumFractionDigits: 2 });
Specify a locale tag as first parameter to control the decimal separator. For a dot, use for example English U.S. locale:
num.toLocaleString("en-US", { maximumFractionDigits: 2, minimumFractionDigits: 2 });
which gives:
1.35
Most countries in Europe use a comma as decimal separator, so if you for example use Swedish/Sweden locale:
num.toLocaleString("sv-SE", { maximumFractionDigits: 2, minimumFractionDigits: 2 });
it will give:
1,35
var num = new Number(14.12);
console.log(num.toPrecision(2)); //outputs 14
console.log(num.toPrecision(3)); //outputs 14.1
console.log(num.toPrecision(4)); //outputs 14.12
console.log(num.toPrecision(5)); //outputs 14.120
I would suggest you use
new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(num)
that way you will also have the local format of a country you specify, plus it would garantee to show exact 2 decimals (whether when num is 1 or 1.12345, it will show 1.00 and 1.12 respectively)
In this example I used German localization, because I wanted my numbers show with thousands delimiter, so this would be some outputs:
1 => 1,00
1.12 => 1,12
1.1234 => 1,12
1234 => 1.234,00
1234.1234 => 1.234,12
For the most accurate rounding, create this function and use it to round to 2 decimal places:
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals).toFixed(decimals);
}
console.log("seeked to " + round(1.005, 2));
> 1.01
Thanks to Razu, this article, and MDN's Math.round reference.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
var number = 123456.789;
console.log(new Intl.NumberFormat('en-IN', {
maximumFractionDigits: 2
}).format(number));
Simplest answer:
var num = 1.2353453;
num.toFixed(2); // 1.24
Example: http://jsfiddle.net/E2XU7/
A much more generic solution for rounding to N places
function roundN(num,n){
return parseFloat(Math.round(num * Math.pow(10, n)) /Math.pow(10,n)).toFixed(n);
}
console.log(roundN(1,2))
console.log(roundN(1.34,2))
console.log(roundN(1.35,2))
console.log(roundN(1.344,2))
console.log(roundN(1.345,2))
console.log(roundN(1.344,3))
console.log(roundN(1.345,3))
console.log(roundN(1.3444,3))
console.log(roundN(1.3455,3))
Output
1.00
1.34
1.35
1.34
1.35
1.344
1.345
1.344
1.346
You are not giving us the whole picture.
javascript:alert(parseFloat(1).toFixed(2)) shows 1.00 in my browsers when I paste it into the location bar.
However if you do something to it afterwards, it will revert.
alert(parseFloat(1).toFixed(2))
var num = 2
document.getElementById('spanId').innerHTML = (parseFloat(num).toFixed(2) - 1)
<span id="spanId"></span>
shows 1 and not 1.00
Are you looking for floor?
var num = 1.42482;
var num2 = 1;
var fnum = Math.floor(num).toFixed(2);
var fnum2 = Math.floor(num2).toFixed(2);
console.log(fnum + " and " + fnum2); //both values will be 1.00
If you're already using jQuery, you could look at using the jQuery Number Format plugin.
The plugin can return formatted numbers as a string, you can set decimal, and thousands separators, and you can choose the number of decimals to show.
$.number( 123, 2 ); // Returns '123.00'
You can also get jQuery Number Format from GitHub.
Is this what you mean?
[edit 20200530] The answer #razu provided is the best imho. So here's a slightly refactored version.
The snippet code will still not return the right value for something like showAsFloat(2.3346) (result 2.33, but should be 2.34). So, see also.
const showAsFloat = (input, decimals = 2, asString = false) => {
if (input === null || input.constructor === Boolean || isNaN(+input)) {
return input;
}
const converted = +( `${Math.round( parseFloat( `${input}e${decimals}` ) )}e-${decimals}` );
return asString ? converted.toFixed(decimals) : converted
};
document.querySelector('#result').textContent = [
'command | result',
'-----------------------------------------------',
'showAsFloat(1); | ' + showAsFloat(1),
'showAsFloat(1.314); | ' + showAsFloat(1.314),
'showAsFloat(\'notanumber\') | ' + showAsFloat('notanumber'),
'showAsFloat(\'23.44567\', 3) | ' + showAsFloat('23.44567', 3),
'showAsFloat(2456198, 5, true)| ' + showAsFloat('24568', 5, true),
'showAsFloat(2456198, 5) | ' + showAsFloat('24568', 5),
'showAsFloat(0, 2, true); | ' + showAsFloat(0, 2, true),
'showAsFloat(1.345); | ' + showAsFloat(1.345),
'showAsFloat(0.005); | ' + showAsFloat(0.005),
'showAsFloat(null); | ' + showAsFloat(null),
].join('\n');
<pre id="result"></pre>
Convert a number into a string, keeping only two decimals:
var num = 5.56789;
var n = num.toFixed(2);
The result of n will be:
5.57
Just run into this one of longest thread, below is my solution:
parseFloat(Math.round((parseFloat(num * 100)).toFixed(2)) / 100 ).toFixed(2)
Let me know if anyone can poke a hole
function currencyFormat (num) {
return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}
console.info(currencyFormat(2665)); // $2,665.00
console.info(currencyFormat(102665)); // $102,665.00
Here's also a generic function that can format to any number of decimal places:
function numberFormat(val, decimalPlaces) {
var multiplier = Math.pow(10, decimalPlaces);
return (Math.round(val * multiplier) / multiplier).toFixed(decimalPlaces);
}
Where specific formatting is required, you should write your own routine or use a library function that does what you need. The basic ECMAScript functionality is usually insufficient for displaying formatted numbers.
A thorough explanation of rounding and formatting is here: http://www.merlyn.demon.co.uk/js-round.htm#RiJ
As a general rule, rounding and formatting should only be peformed as a last step before output. Doing so earlier may introduce unexpectedly large errors and destroy the formatting.
here is another solution to round only using floor, meaning, making sure calculated amount won't be bigger than the original amount (sometimes needed for transactions):
Math.floor(num* 100 )/100;
Good news!!!!!
It seems that the new version of javascript, ES2020 (I'm using just), provided new behavior of this function.
let ff:number =3
console.info(ff.toFixed(2)) //3.00
as desired.
function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){
var numbers = string.toString().match(/\d+/g).join([]);
numbers = numbers.padStart(decimals+1, "0");
var splitNumbers = numbers.split("").reverse();
var mask = '';
splitNumbers.forEach(function(d,i){
if (i == decimals) { mask = decimal + mask; }
if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; }
mask = d + mask;
});
return pre + mask + pos;
}
var element = document.getElementById("format");
var money= number_format("10987654321",2,',','.');
element.innerHTML = money;
#format{
display:inline-block;
padding:10px;
border:1px solid #ddd;
background:#f5f5f5;
}
<div id='format'>Test 123456789</div>
Try below code:
function numberWithCommas(number) {
var newval = parseFloat(Math.round(number * 100) / 100).toFixed(2);
return newval.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
var quantity = 12;
var import1 = 12.55;
var total = quantity * import1;
var answer = parseFloat(total).toFixed(2);
document.write(answer);
I had to decide between the parseFloat() and Number() conversions before I could make toFixed() call. Here's an example of a number formatting post-capturing user input.
HTML:
<input type="number" class="dec-number" min="0" step="0.01" />
Event handler:
$('.dec-number').on('change', function () {
const value = $(this).val();
$(this).val(value.toFixed(2));
});
The above code will result in TypeError exception. Note that although the html input type is "number", the user input is actually a "string" data type. However, toFixed() function may only be invoked on an object that is a Number.
My final code would look as follows:
$('.dec-number').on('change', function () {
const value = Number($(this).val());
$(this).val(value.toFixed(2));
});
The reason I favor to cast with Number() vs. parseFloat() is because I don't have to perform an extra validation neither for an empty input string, nor NaN value. The Number() function would automatically handle an empty string and covert it to zero.
var num1 = "0.1";
document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2);
var num2 = "1.341";
document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);
var num3 = "1.345";
document.getElementById('num3').innerHTML = (Math.round(num3 * 100) / 100).toFixed(2);
span {
border: 1px solid #000;
margin: 5px;
padding: 5px;
}
<span id="num1"></span>
<span id="num2"></span>
<span id="num3"></span>
RegExp - alternative approach
On input you have string (because you use parse) so we can get result by using only string manipulations and integer number calculations
let toFix2 = (n) => n.replace(/(-?)(\d+)\.(\d\d)(\d+)/, (_,s,i,d,r)=> {
let k= (+r[0]>=5)+ +d - (r==5 && s=='-');
return s + (+i+(k>99)) + "." + ((k>99)?"00":(k>9?k:"0"+k));
})
// TESTs
console.log(toFix2("1"));
console.log(toFix2("1.341"));
console.log(toFix2("1.345"));
console.log(toFix2("1.005"));
Explanation
s is sign, i is integer part, d are first two digits after dot, r are other digits (we use r[0] value to calc rounding)
k contains information about last two digits (represented as integer number)
if r[0] is >=5 then we add 1 to d - but in case when we have minus number (s=='-') and r is exact equal to 5 then in this case we substract 1 (for compatibility reasons - in same way Math.round works for minus numbers e.g Math.round(-1.5)==-1)
after that if last two digits k are greater than 99 then we add one to integer part i
You can use numeral.js.
numeral(1.341).format('0.00') // 1.34
numeral(1.345).format('0.00') // 1.35
I do like:
var num = 12.749;
parseFloat((Math.round(num * 100) / 100).toFixed(2)); // 123.75
Round the number with 2 decimal points,
then make sure to parse it with parseFloat()
to return Number, not String unless you don't care if it is String or Number.
Extend Math object with precision method
Object.defineProperty(Math, 'precision',{
value: function (value,precision,type){
var v = parseFloat(value),
p = Math.max(precision,0)||0,
t = type||'round';
return (Math[t](v*Math.pow(10,p))/Math.pow(10,p)).toFixed(p);
}
});
console.log(
Math.precision(3.1,3), // round 3 digits
Math.precision(0.12345,2,'ceil'), // ceil 2 digits
Math.precision(1.1) // integer part
)

How to convert hex to decimal WITH A LOOP in JavaScript

Is it possible to convert a hex number to a decimal number with a loop?
Example: input "FE" output "254"
I looked at those questions :
How to convert decimal to hex in JavaScript?
Writing a function to convert hex to decimal
Writing a function to convert hex to decimal
Writing a function to convert hex to decimal
How to convert hex to decimal in R
How to convert hex to decimal in c#.net?
And a few more that were not related to JS or loops. I searched for a solution in other languages too in case that I find a way to do it,but I didn't. The first one was the most useful one. Maybe I can devide by 16,compare the result to preset values and print the result, but I want to try with loops. How can I do it?
Maybe you are looking for something like this, knowing that it can be done with a oneliner (with parseInt)?
function hexToDec(hex) {
var result = 0, digitValue;
hex = hex.toLowerCase();
for (var i = 0; i < hex.length; i++) {
digitValue = '0123456789abcdef'.indexOf(hex[i]);
result = result * 16 + digitValue;
}
return result;
}
console.log(hexToDec('FE'));
Alternative
Maybe you want to have a go at using reduce, and ES6 arrow functions:
function hexToDec(hex) {
return hex.toLowerCase().split('').reduce( (result, ch) =>
result * 16 + '0123456789abcdefgh'.indexOf(ch), 0);
}
console.log(hexToDec('FE'));
Just another way to do it...
// The purpose of the function is to convert Hex to Decimal.
// This is done by adding each of the converted values.
function hextoDec(val) {
// Reversed the order because the added values need to 16^i for each value since 'F' is position 1 and 'E' is position 0
var hex = val.split('').reverse().join('');
// Set the Decimal variable as a integer
var dec = 0;
// Loop through the length of the hex to iterate through each character
for (i = 0; i < hex.length; i++) {
// Obtain the numeric value of the character A=10 B=11 and so on..
// you could also change this to var conv = parseInt(hex[i], 16) instead
var conv = '0123456789ABCDEF'.indexOf(hex[i]);
// Calculation performed is the converted value * (16^i) based on the position of the character
// This is then added to the original dec variable. 'FE' for example
// in Reverse order [E] = (14 * (16 ^ 0)) + [F] = (15 * (16 ^ 1))
dec += conv * Math.pow(16, i);
}
// Returns the added decimal value
return dec;
}
console.log(hextoDec('FE'));
Sorry that was backwards, and I can't find where to edit answer, so here is corrected answer:
function doit(hex) {
var num = 0;
for(var x=0;x<hex.length;x++) {
var hexdigit = parseInt(hex[x],16);
num = (num << 4) | hexdigit;
}
return num;
}
If you want to loop over every hex digit, then just loop from end to beginning, shifting each digit 4 bits to the left as you add them (each hex digit is four bits long):
function doit(hex) {
var num = 0;
for(var x=0;x<hex.length;x++) {
var hexdigit = parseInt(hex[x],16);
num = (num << 4) | hexdigit;
}
return num;
}
JavaScript can natively count in hex. I'm finding out the hard way that, in a loop, it converts hex to decimal, so for your purposes, this is great.
prepend your hex with 0x , and you can directly write a for loop.
For example, I wanted get an array of hex values for these unicode characters, but I am by default getting an array of decimal values.
Here's sample code that is converting unicode hex to dec
var arrayOfEmojis = [];
// my range here is in hex format
for (var i=0x1F600; i < 0x1F64F; i++) {
arrayOfEmojis.push('\\u{' + i + '}');
}
console.log(arrayOfEmojis.toString()); // this outputs an array of decimals

How do i return a number excluding the last digit?

So I have a number like 5467. I want my code to return 546.
I tried taking the last number and subtracting it from the original number but I get 5460 instead of 546.
Combine / with %:
(5467 - (5467 % 10)) / 10
564
Sounds like you also need to divide my 10. You could do something like this:
var number = 5467;
number = number - (number % 10); // This will subtract off the last digit.
number = number / 10;
console.log(number); // 546
We first use the modulo operator % to get the last digit, and we subtract it from number. That reduces the number from 5467 to 5460. Now to chop off the last digit (which is guaranteed to be a 0) we divide by 10 and get 546.
Written more concisely you could do:
number = (number - ( number % 10)) / 10;
There's a few things you can do the most concise being:
Math.floor(num / 10);
Or, convert to a string, remove the last character and convert back to number.
parseInt(num.toString().slice(0, -1));
If string representation would be fine for you then one other way is
var num = 5467,
cut = (num/10).toFixed(); // <-'547'
Well... warning..! i have to say toFixed() method rounds if necessary. So in this particular example it doesn't work.
I dont mind some of the other answers, but i feel that this maybe too fixed on it being a number.
Which it is, but you want to remove the last digit/char, regardless of the number, so why not substr?
http://www.w3schools.com/jsref/jsref_substr.asp
var s = 5467;
s = s.toString().substr(0, s.toString().length - 1);
console.log(s)
or even easier:
var s = (5467).toString();
s = s.substr(0, s.length - 1);
console.log(s)
These dont take into account single digit numbers, so passing in 1 would return blank. To answer that you could simply do a check like:
var s = (1).toString();
if(s.length > 1)
s = s.substr(0, s.length - 1);
console.log(s)
Also, similar question to:
Remove last digits from an int
Remove the last digits of a number (not string)
Removing the last digits in string
To truncate digits from the right hand side until the number is less than 30, keep dividing by 10 and rounding down until a suitable value is reached:
var n = 12341235;
while (n > 30) n = n/10|0;
document.write(n);
The greater than and division operations will coerce n to a number, so it can be a number or string. If ToNumber(n) results in NaN (e.g. n = 'foo'), then the value of n is not modified.
You can simply divide the number by 10 and parseInt()
var num = 5467;
num = parseInt(num/10);
Update :
To repeat the process until the answer is less than 30, use while loop as
var num = 5467;
while(num >= 30) {
num = parseInt(num/10);
}
document.write(num);

Spliting the binary string in half

I am trying to split binary number in half and then just add 4 zeroes.
For example for 10111101 I want to end up with only the first half of the number and make the rest of the number zeroes. What I want to end up would be 10110000.
Can you help me with this?
Use substring to split and then looping to pad
var str = '10111101';
var output = str.substring( 0, str.length/2 );
for ( var counter = 0; counter < str.length/2; counter++ )
{
output += "0";
}
alert(output)
try this (one-liner)
var binary_str = '10111101';
var padded_binary = binary_str.slice(0, binary_str.length/2) + new Array(binary_str.length/2+1).join('0');
console.log([binary_str,padded_binary]);
sample output
['10111101','10110000']
I guess you are using JavaScript...
"10111101".substr(0, 4) + "0000";
It's a bit unclear if you are trying to operate on numbers or strings. The answers already given do a good job of showing how to operate on a strings. If you want to operate with numbers only, you can do something like:
// count the number of leading 0s in a 32-bit word
function nlz32 (word) {
var count;
for (count = 0; count < 32; count ++) {
if (word & (1 << (31 - count))) {
break;
}
}
return count;
}
function zeroBottomHalf (num) {
var digits = 32 - nlz32(num); // count # of digits in num
var half = Math.floor(digits / 2);// how many to set to 0
var lowerMask = (1 << half) - 1; //mask for lower bits: 0b00001111
var upperMask = ~lowerMask //mask for upper bits: 0b11110000
return num & upperMask;
}
var before = 0b10111101;
var after = zeroBottomHalf(before);
console.log('before = ', before.toString(2)); // outputs: 10111101
console.log('after = ', after.toString(2)); // outputs: 10110000
In practice, it is probably simplest to covert your number to a string with num.toString(2), then operate on it like a string as in one of the other answers. At the end you can convert back to a number with parseInt(str, 2)
If you have a real number, not string, then just use binary arithmetic. Assuming your number is always 8 binary digits long - your question is kinda vague on that - it'd be simply:
console.log((0b10111101 & 0b11110000).toString(2))
// 10110000

Get each digit of a number

What's the best way to get the Nth digit of a number in javascript?
For example, for 31415926, the function will return 1 if N=2.
EDIT: And if possible, tu return directly a number, not a string.
EDIT 2: It is from left to right.
Try with that : (''+number)[nth] or (''+number)[nth-1] if one-based.
Personally, I would use:
function getNthDigit(number, n){
return parseInt((""+number).charAt(n));
}
But if you don't want it to be in String form ever you could use:
function getNthDigit(number, n){
var num = number,
digits = 0;
do{
num /= 10;
digits++;
}while(num>=1);
num = number / Math.pow(10, (digits - n));
num -= num % 1;
return (num % 10);
}
On second thought, just use the first option.
UPDATE: I didn't consider the fact that it was counting from the right. My bad!
Anyway, considering that the input is STILL a string, I'd use the same function, just with a little tweak.
Why don't you use the CharAt function? I think is the best option, considering the risk of multi-byte strings!!!
EDIT: I forgot the example:
var str = "1234567";
var n = str.charAt(str.length-2); // n is "6"

Categories