How to create binary to decimal in JavaScript without parseInt() [duplicate] - javascript

This question already has answers here:
How to convert binary string to decimal?
(10 answers)
Closed 3 years ago.
I was trying to create a binary to decimal converter without using parseInt ()
Heres my code :
var inp = `110010`;
var len = inp.length;
var string = inp.split("");
var counter = string.map(function(val,i){
return i;
}).reverse();
var storeBin = string.map(function(val,i){
let x ="";
if(val>0){
x += 2;
}else if(val===0){
x += 0;
}
return Math.pow(string[i]*x,counter[i]);
});
var dec=0; /* output */
for(i=0;i<len;i++){
dec += storeBin[i]
}
console.log("Entered binary "+inp);
console.log("Decimal "+dec);
When I run it:
Input: 1010
Output: Entered binary 1010
Decimal 11
But the output of binary 1010 should be 10 now 11 can someone please help me find the issue in this code

You need to do it like return val * Math.pow(2, counter[i]);.
var inp = `110010`;
var len = inp.length;
var string = inp.split("");
var counter = string.map(function(val, i) {
return i;
}).reverse();
var storeBin = string.map(function(val, i) {
return val * Math.pow(2, counter[i]);
});
var dec = 0; /* output */
for (i = 0; i < len; i++) {
dec += storeBin[i]
}
console.log("Entered binary " + inp);
console.log("Decimal " + dec);
FYI :
The correspomding deciaml number to a binary number is the sum of binary digits (dn) times their power of 2 (2^n):
decimalNum = d0 × 2^0 + d1 × 2^1 + d2 × 2^2 + ...
Even you can make it more simpler by using the Array#reduce method.
var inp = `110010`;
var dec = inp.split('').reduce(function(val, d, i, arr) {
return val + Math.pow(2, arr.length - i - 1) * d;
}, 0);
console.log("Entered binary " + inp);
console.log("Decimal " + dec);
Or with Array#reverse method.
var inp = `110010`;
var dec = inp.split('').reverse().reduce(function(val, d, i) {
return val + Math.pow(2, i) * d;
}, 0);
console.log("Entered binary " + inp);
console.log("Decimal " + dec);

Related

How to integrate loops with arrays?

I'm prompting the user to enter a number between 50 and 100.
(Default value for the prompt is 100.)
The input, minus one, is then displayed on the screen followed by spaces.
Fore example, if user enters 60, this is what I want to be displayed:
01 02 03 04
05 06 07 08
...
53 54 55 56
57 58 59
So far I'v done the following, but I can't figure out the problem or what to do next:
num = Number(prompt("Please enter a number between 50 and 100"));
var arr= new Array(parseInt(arrayLength));
for (var i = 0; i < array.length; i++) {
document.getElementById("myDiv").innerHTML = arr[i];
}
You can just parseInt on the return value from the "prompt", and then you can create an array that is mappable. Once that is done, you can just join the entire array with a space, which will give you 1 2 3 ... etc.
If you are looking for the most basic format where there are no line-breaks, this is a simple version:
var num = parseInt(prompt('Please enter a number between 50 and 100')) || 100;
var arr = Array.apply(null, Array(num - 1))
.map(function(x, i) {
return i + 1;
});
document.getElementById("myDiv").innerHTML = arr.join(' ');
<div id="myDiv"></div>
Otherwise, if you are looking for the more complex formatting and with the line breaks, here is the same concept modified a little bit:
var num = parseInt(prompt('Please enter a number between 50 and 100')) || 100;
var arr = Array.apply(null, Array(num - 1))
.map(function(x, i) {
var actual = i + 1;
if (actual < 10) {
actual = '0' + actual;
}
if (i % 4 === 3) {
actual += '<br>';
}
return actual;
});
document.getElementById("myDiv").innerHTML = arr.join(' ');
<div id="myDiv"></div>
You can concatenate a string with the numbers and then set the innerHtml of your div to that string:
num = Number(prompt("Please enter a number between 50 and 100"));
var result = "";
for (var i = 1; i < num; i++) {
result += i + " ";
}
document.getElementById("myDiv").innerHTML = result;
If you want the numbers 1-9 to be displayed like 01 02 03... you can do so with this version:
num = Number(prompt("Please enter a number between 50 and 100"));
var result = "";
for (var i = 1; i < num; i++) {
if(i < 10){
result += "0" + i + " ";
}else{
result += i + " ";
}
}
document.getElementById("myDiv").innerHTML = result;
See this Fiddle as reference.
This is how I would do it. I don't know why you need the array?
Just loop from start to end and add spaces after each number (while padding it) and add line breaks after every 4th number.
var num = Number(prompt("Please enter a number between 50 and 100")) || 100;
document.getElementById("myDiv").innerHTML = generateText(num, 4);
function generateText(n, cols) {
var result = '';
for (var i = 1; i < n; i++) {
result += pad(i, 2, '0') + ' ';
if (i % cols === 0) {
result += '<br />';
}
}
return result;
}
function pad(val, n, ch) {
val = '' + val;
while (val.length < n) {
val = ch + val;
}
return val;
}
<div id="myDiv"></div>
Since we are going for brevity here. /s
Here is some "code golf" to scratch your itch :)
var num = Number(prompt("Please enter a number between 50 and 100")) || 100;
num = num < 50 ? 50 : (num > 100 ? 100 : num);
document.getElementById('myDiv').innerHTML = Array
.apply(null, Array(num - 1))
.map(function(x, i) { return (i < 9 ? '0' : '') + (i + 1); })
.reduce(function(s, x, i) { return s + x + (i % 4 === 3 ? '<br />' : ' '); }, '');
<div id="myDiv"></div>

Add two timestamps of format "HH+:MM:SS"

So basically i have two strings of timestamps which i want to add:
a = "00:10:12";
aParts = a.split(/:/);
b = "00:30:34";
bParts = b.split(/:/);
time1 = 3600000 * parseInt(aParts[0]) + 60000 * parseInt(aParts[1]) + 1000 * parseInt(aParts[2]);
time2 = 3600000 * parseInt(bParts[0]) + 60000 * parseInt(bParts[1]) + 1000 * parseInt(bParts[2]);
dateTime = time1 + time2;
hours = parseInt(dateTime/3600000);
dateTime = parseInt(dateTime%3600000);
minutes = parseInt(dateTime/60000);
dateTime = parseInt(dateTime%60000);
seconds = parseInt(dateTime/1000);
newTime = addLeadingZeros(hours,2) + ':' + addLeadingZeros(minutes,2) + ':' + addLeadingZeros(seconds,2);
// returns correct "00:40:46"
function addLeadingZeros (n, length){
var str = (n > 0 ? n : -n) + "";
var zeros = "";
for (var i = length - str.length; i > 0; i--)
zeros += "0";
zeros += str;
return n >= 0 ? zeros : "-" + zeros;
}
While writing this question i managed to come up with the above code :-) that works somehow - is that a proper way of adding two string timestamps or is there a better approach?
Forgot to mention - i did try converting the two strings into Date objects and using .getTime() adding the two datetimes - but that gives me a wrong time in the date.
There is nothing notably wrong with your code, but be sure to set the radix when using parseInt
radix
An integer that represents the radix of the value to parse. Always
specify this parameter to eliminate reader confusion
and to guarantee predictable behavior. Different implementations
produce different results when a radix is not specified.
There is no standard method for performing the task that you have described.
Here is an example that I have used in the past.
Javascript
/*jslint maxerr: 50, indent: 4, browser: true, devel: true */
(function () {
"use strict";
function zeroPad(num) {
var str = num.toString();
if (num < 2) {
str = "0" + str;
}
return str;
}
function addTimes() {
if (!arguments.length) {
throw new SyntaxError("No arguments provided.");
}
var total = {
hours: 0,
minutes: 0,
seconds: 0
},
argIndex,
argLength,
time,
parts,
part,
partIndex,
temp;
for (argIndex = 0, argLength = arguments.length; argIndex < argLength; argIndex += 1) {
time = arguments[argIndex];
if (typeof time !== "string") {
throw new TypeError("Argument must be a string.");
}
parts = time.split(":");
if (parts.length !== 3) {
throw new SyntaxError("Argument is incorrectly formatted.");
}
for (partIndex = 0; partIndex < 3; partIndex += 1) {
part = parts[partIndex];
if (partIndex < 2) {
if (part === "" || !/^\d*$/.test(part)) {
throw new SyntaxError("Argument is incorrectly formatted.");
}
parts[partIndex] = parseInt(part, 10);
} else {
if (part === "" || !/^\d*\.?\d+$/.test(part)) {
throw new SyntaxError("Argument is incorrectly formatted.");
}
parts[partIndex] = parseFloat(part);
}
}
temp = (parts[2] + total.seconds);
total.seconds = temp % 60;
temp = (parts[1] + total.minutes) + (temp - total.seconds) / 60;
total.minutes = temp % 60;
total.hours = (parts[0] + total.hours) + (temp - total.minutes) / 60;
}
return zeroPad(total.hours) + ":" + zeroPad(total.minutes) + ":" + zeroPad(total.seconds);
}
var a = "00:10:12",
b = "00:30:34",
c = "10:40:40";
console.log(addTimes(a, b, c));
}());
Output
11:21:26
On jsfiddle

Unexpected result when converting decimal to fraction

function gcd(a, b) {
return (b) ? gcd(b, a % b) : a;
}
var dec2Frac = function (d) {
var top = d.toString().replace(/\d+[.]/, '');
var bot = Math.pow(10, top.length);
if (d > 1) {
top = +top + Math.floor(d) * bot;
}
var x = gcd(top, bot);
var r1 = top / x;
var r2 = bot / x;
var frac = r1 + "/" + r2;
var parts = frac.split('/');
var simpler = parts[0][0]+'/'+parts[1][0];
return simpler;
};
If I input 640x960 = 0.66666666666667
I'm expecting the result to be 2/3 as evident here: http://www.mindspring.com/~alanh/fracs.html
Instead this function returns 6/1. Test here: http://jsbin.com/asoxud/1/
As an addition to MvG's Answer,
I found this quite interesting and wanted to understand how floating points are stored and how to get back an fraction of a float to maybe do calculations with them.
It gave a bit of brainache trying to figure this out on my own, but as it made click, i came up with this Fraction function,
I don't know if this helps you or not, but
now that its written anyway , why not leave it here
function Fraction(n, d) {
if ("number" !== typeof n)
throw new TypeError("Excptected Parameter to be of type number");
var strings = n.toString(2).split("."); //Split the number by its decimal point
if (strings.length > 1 && !d) { //No denominator given and n is a float
var floats = [strings[1].substr(0, 27), strings[1].substr(27, 54)]; //Split into to parts
var int64 = [
parseInt(floats[0], 2) << 1,
parseInt(floats[1], 2) << 1
];
var denominator = Math.pow(2, strings[1].length + 1); //
var numerator = int64[0] * Math.pow(2, floats[1].length);
numerator += int64[1];
numerator += parseInt(strings[0], 2) * denominator;
this.numerator = numerator;
this.denominator = denominator;
this.reduce();
this.approx = approx(n);
} else if (strings.length < 2 && !d) { // If no denominator and n is an int
this.numerator = n;
this.denominator = 1;
} else { //if n and d
this.numerator = n;
this.denominator = d;
}
function approx(f, n) {
n = n || 0;
var fraction = new Fraction(1, 1);
var float = Math.pow(f, -1);
var rec = ~~float;
var decimal = float - rec;
if (float.toPrecision(Fraction.precision) == rec)
return new Fraction(1, rec);
var _fraction = approx(decimal, n + 1);
fraction.denominator = rec * _fraction.denominator + _fraction.numerator;
fraction.numerator = _fraction.denominator;
return fraction;
}
}
//The approx precision
Fraction.precision = 10;
Fraction.prototype.toString = function () {
return this.numerator + "/" + this.denominator;
};
Fraction.prototype.gcd = function () {
return (function gcd(u, v) {
return ((u > 0) ? gcd(v % u, u) : v);
})(this.numerator, this.denominator);
};
Fraction.prototype.reduce = function () {
var _gcd = this.gcd();
this.numerator /= _gcd;
this.denominator /= _gcd;
};
Fraction.prototype.valueOf = function () {
return this.numerator / this.denominator;
};
var f = new Fraction(0.3333);
+ f; //0.3333333333
f.toString(); // 6004799502560181/18014398509481984
+ f.approx //0.33333
+ f.approx.toString() //3333/10000
var g = new Fraction(2 / 3);
+ g; //0.6666666666666666
g.toString(); //6004799503160661/9007199254740992
+ g.approx //0.6666666666666666
+ g.approx.toString() //2/3
Heres a JSbin as well
Your floating point numbers are approximations of the rational numbers you hope for. See e.g. Is floating point math broken? for details on this. The upshoot is: you can't hope to actually find a numerator and denominator which represent your original fraction.
If you want that fraction, you should have a look at continued fractions. Each truncated continued fraction will represent the best possible rational approximation for an arbitrary value. You can continue this until the error is sufficiently small.
Here is a page visualizing this approximation. The text is in German, but the maths should be clear enough. This page is in English but doesn't have as much visualization.

Javascript: convert a (hex) signed integer to a javascript value

I have a signed value given as a hex number, by example 0xffeb and want convert it into -21 as a "normal" Javascript integer.
I have written some code so far:
function toBinary(a) { //: String
var r = '';
var binCounter = 0;
while (a > 0) {
r = a%2 + r;
a = Math.floor(a/2);
}
return r;
}
function twoscompl(a) { //: int
var l = toBinaryFill(a).length;
var msb = a >>> (l-1);
if (msb == 0) {
return a;
}
a = a-1;
var str = toBinary(a);
var nstr = '';
for (var i = 0; i < str.length; i++) {
nstr += str.charAt(i) == '1' ? '0' : '1';
}
return (-1)*parseInt(nstr);
}
The problem is, that my function returns 1 as MSB for both numbers because only at the MSB of the binary representation "string" is looked. And for this case both numbers are 1:
-21 => 0xffeb => 1111 1111 1110 1011
21 => 0x15 => 1 0101
Have you any idea to implement this more efficient and nicer?
Greetings,
mythbu
Use parseInt() to convert (which just accepts your hex string):
parseInt(a);
Then use a mask to figure out if the MSB is set:
a & 0x8000
If that returns a nonzero value, you know it is negative.
To wrap it all up:
a = "0xffeb";
a = parseInt(a, 16);
if ((a & 0x8000) > 0) {
a = a - 0x10000;
}
Note that this only works for 16-bit integers (short in C). If you have a 32-bit integer, you'll need a different mask and subtraction.
I came up with this
function hexToInt(hex) {
if (hex.length % 2 != 0) {
hex = "0" + hex;
}
var num = parseInt(hex, 16);
var maxVal = Math.pow(2, hex.length / 2 * 8);
if (num > maxVal / 2 - 1) {
num = num - maxVal
}
return num;
}
And usage:
var res = hexToInt("FF"); // -1
res = hexToInt("A"); // same as "0A", 10
res = hexToInt("FFF"); // same as "0FFF", 4095
res = hexToInt("FFFF"); // -1
So basically the hex conversion range depends on hex's length, ant this is what I was looking for. Hope it helps.
Based on #Bart Friederichs I've come with:
function HexToSignedInt(num, numSize) {
var val = {
mask: 0x8 * Math.pow(16, numSize-1), // 0x8000 if numSize = 4
sub: -0x1 * Math.pow(16, numSize) //-0x10000 if numSize = 4
}
if((parseInt(num, 16) & val.mask) > 0) { //negative
return (val.sub + parseInt(num, 16))
}else { //positive
return (parseInt(num,16))
}
}
so now you can specify the exact length (in nibbles).
var numberToConvert = "CB8";
HexToSignedInt(numberToConvert, 3);
//expected output: -840
function hexToSignedInt(hex) {
if (hex.length % 2 != 0) {
hex = "0" + hex;
}
var num = parseInt(hex, 16);
var maxVal = Math.pow(2, hex.length / 2 * 8);
if (num > maxVal / 2 - 1) {
num = num - maxVal
}
return num;
}
function hexToUnsignedInt(hex){
return parseInt(hex,16);
}
the first for signed integer and
the second for unsigned integer
As I had to turn absolute numeric values to int32 values that range from -2^24 to 2^24-1,
I came up with this solution, you just have to change your input into a number through parseInt(hex, 16), in your case, nBytes is 2.
function toSignedInt(value, nBytes) { // 0 <= value < 2^nbytes*4, nBytes >= 1,
var hexMask = '0x80' + '00'.repeat(nBytes - 1);
var intMask = parseInt(hexMask, 16);
if (value >= intMask) {
value = value - intMask * 2;
}
return value;
}
var vals = [ // expected output
'0x00', // 0
'0xFF', // 255
'0xFFFFFF', // 2^24 - 1 = 16777215
'0x7FFFFFFF', // 2^31 -1 = 2147483647
'0x80000000', // -2^31 = -2147483648
'0x80000001', // -2^31 + 1 = -2147483647
'0xFFFFFFFF', // -1
];
for (var hex of vals) {
var num = parseInt(hex, 16);
var result = toSignedInt(num, 4);
console.log(hex, num, result);
}
var sampleInput = '0xffeb';
var sampleResult = toSignedInt(parseInt(sampleInput, 16), 2);
console.log(sampleInput, sampleResult); // "0xffeb", -21
Based on the accepted answer, expand to longer number types:
function parseSignedShort(str) {
const i = parseInt(str, 16);
return i >= 0x8000 ? i - 0x10000 : i;
}
parseSignedShort("0xffeb"); // -21
function parseSignedInt(str) {
const i = parseInt(str, 16);
return i >= 0x80000000 ? i - 0x100000000 : i;
}
parseSignedInt("0xffffffeb"); // -21
// Depends on new JS feature. Only supported after ES2020
function parseSignedLong(str) {
if (!str.toLowerCase().startsWith("0x"))
str = "0x" + str;
const i = BigInt(str);
return Number(i >= 0x8000000000000000n ? i - 0x10000000000000000n : i);
}
parseSignedLong("0xffffffffffffffeb"); // -21

How to format numbers? [duplicate]

This question already has answers here:
How to format numbers as currency strings
(67 answers)
Closed 3 years ago.
I want to format numbers using JavaScript.
For example:
10 => 10.00
100 => 100.00
1000 => 1,000.00
10000 => 10,000.00
100000 => 100,000.00
If you want to use built-in code, you can use toLocaleString() with minimumFractionDigits.
Browser compatibility for the extended options on toLocaleString() was limited when I first wrote this answer, but the current status looks good. If you're using Node.js, you will need to npm install the intl package.
var value = (100000).toLocaleString(
undefined, // leave undefined to use the visitor's browser
// locale or a string like 'en-US' to override it.
{ minimumFractionDigits: 2 }
);
console.log(value);
Number formatting varies between cultures. Unless you're doing string comparison on the output,1 the polite thing to do is pick undefined and let the visitor's browser use the formatting they're most familiar with.2
// Demonstrate selected international locales
var locales = [
undefined, // Your own browser
'en-US', // United States
'de-DE', // Germany
'ru-RU', // Russia
'hi-IN', // India
'de-CH', // Switzerland
];
var n = 100000;
var opts = { minimumFractionDigits: 2 };
for (var i = 0; i < locales.length; i++) {
console.log(locales[i], n.toLocaleString(locales[i], opts));
}
If you are from a culture with a different format from those above, please edit this post and add your locale code.
1 Which you shouldn't.
2 Obviously do not use this for currency with something like {style: 'currency', currency: 'JPY'} unless you have converted to the local exchange rate. You don't want your website to tell people the price is ¥300 when it's really $300. Sometimes real e-commerce sites make this mistake.
Use
num = num.toFixed(2);
Where 2 is the number of decimal places
Edit:
Here's the function to format number as you want
function formatNumber(number)
{
number = number.toFixed(2) + '';
x = number.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Sorce: www.mredkj.com
Short solution:
var n = 1234567890;
String(n).replace(/(.)(?=(\d{3})+$)/g,'$1,')
// "1,234,567,890"
On browsers that support the ECMAScript® 2016 Internationalization API Specification (ECMA-402), you can use an Intl.NumberFormat instance:
var nf = Intl.NumberFormat();
var x = 42000000;
console.log(nf.format(x)); // 42,000,000 in many locales
// 42.000.000 in many other locales
if (typeof Intl === "undefined" || !Intl.NumberFormat) {
console.log("This browser doesn't support Intl.NumberFormat");
} else {
var nf = Intl.NumberFormat();
var x = 42000000;
console.log(nf.format(x)); // 42,000,000 in many locales
// 42.000.000 in many other locales
}
Due to the bugs found by JasperV — good points! — I have rewritten my old code. I guess I only ever used this for positive values with two decimal places.
Depending on what you are trying to achieve, you may want rounding or not, so here are two versions split across that divide.
First up, with rounding.
I've introduced the toFixed() method as it better handles rounding to specific decimal places accurately and is well support. It does slow things down however.
This version still detaches the decimal, but using a different method than before. The w|0 part removes the decimal. For more information on that, this is a good answer. This then leaves the remaining integer, stores it in k and then subtracts it again from the original number, leaving the decimal by itself.
Also, if we're to take negative numbers into account, we need to while loop (skipping three digits) until we hit b. This has been calculated to be 1 when dealing with negative numbers to avoid putting something like -,100.00
The rest of the loop is the same as before.
function formatThousandsWithRounding(n, dp){
var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,
u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),
s = ''+k, i = s.length, r = '';
while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }
return s.substr(0, i + 3) + r + (d ? '.'+d: '');
};
In the snippet below you can edit the numbers to test yourself.
function formatThousandsWithRounding(n, dp){
var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,
u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),
s = ''+k, i = s.length, r = '';
while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }
return s.substr(0, i + 3) + r + (d ? '.'+d: '');
};
var dp;
var createInput = function(v){
var inp = jQuery('<input class="input" />').val(v);
var eql = jQuery('<span> = </span>');
var out = jQuery('<div class="output" />').css('display', 'inline-block');
var row = jQuery('<div class="row" />');
row.append(inp).append(eql).append(out);
inp.keyup(function(){
out.text(formatThousandsWithRounding(Number(inp.val()), Number(dp.val())));
});
inp.keyup();
jQuery('body').append(row);
return inp;
};
jQuery(function(){
var numbers = [
0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999
], inputs = $();
dp = jQuery('#dp');
for ( var i=0; i<numbers.length; i++ ) {
inputs = inputs.add(createInput(numbers[i]));
}
dp.on('input change', function(){
inputs.keyup();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />
Now the other version, without rounding.
This takes a different route and attempts to avoid mathematical calculation (as this can introduce rounding, or rounding errors). If you don't want rounding, then you are only dealing with things as a string i.e. 1000.999 converted to two decimal places will only ever be 1000.99 and not 1001.00.
This method avoids using .split() and RegExp() however, both of which are very slow in comparison. And whilst I learned something new from Michael's answer about toLocaleString, I also was surprised to learn that it is — by quite a way — the slowest method out of them all (at least in Firefox and Chrome; Mac OSX).
Using lastIndexOf() we find the possibly existent decimal point, and from there everything else is pretty much the same. Save for the padding with extra 0s where needed. This code is limited to 5 decimal places. Out of my test this was the faster method.
var formatThousandsNoRounding = function(n, dp){
var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,
i = s.lastIndexOf('.'), j = i == -1 ? l : i,
r = e, d = s.substr(j+1, dp);
while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }
return s.substr(0, j + 3) + r +
(dp ? '.' + d + ( d.length < dp ?
('00000').substr(0, dp - d.length):e):e);
};
var formatThousandsNoRounding = function(n, dp){
var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,
i = s.lastIndexOf('.'), j = i == -1 ? l : i,
r = e, d = s.substr(j+1, dp);
while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }
return s.substr(0, j + 3) + r +
(dp ? '.' + d + ( d.length < dp ?
('00000').substr(0, dp - d.length):e):e);
};
var dp;
var createInput = function(v){
var inp = jQuery('<input class="input" />').val(v);
var eql = jQuery('<span> = </span>');
var out = jQuery('<div class="output" />').css('display', 'inline-block');
var row = jQuery('<div class="row" />');
row.append(inp).append(eql).append(out);
inp.keyup(function(){
out.text(formatThousandsNoRounding(Number(inp.val()), Number(dp.val())));
});
inp.keyup();
jQuery('body').append(row);
return inp;
};
jQuery(function(){
var numbers = [
0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999
], inputs = $();
dp = jQuery('#dp');
for ( var i=0; i<numbers.length; i++ ) {
inputs = inputs.add(createInput(numbers[i]));
}
dp.on('input change', function(){
inputs.keyup();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />
I'll update with an in-page snippet demo shortly, but for now here is a fiddle:
https://jsfiddle.net/bv2ort0a/2/
Old Method
Why use RegExp for this? — don't use a hammer when a toothpick will do i.e. use string manipulation:
var formatThousands = function(n, dp){
var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
while ( (i -= 3) > 0 ) { r = ',' + s.substr(i, 3) + r; }
return s.substr(0, i + 3) + r +
(d ? '.' + Math.round(d * Math.pow(10, dp || 2)) : '');
};
walk through
formatThousands( 1000000.42 );
First strip off decimal:
s = '1000000', d = ~ 0.42
Work backwards from the end of the string:
',' + '000'
',' + '000' + ',000'
Finalise by adding the leftover prefix and the decimal suffix (with rounding to dp no. decimal points):
'1' + ',000,000' + '.42'
fiddlesticks
http://jsfiddle.net/XC3sS/
Use the Number function toFixed and this function to add the commas.
function addCommas(nStr)
{
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
n = 10000;
r = n.toFixed(2); //10000.00
addCommas(r); // 10,000.00
http://www.mredkj.com/javascript/numberFormat.html
I think with this jQuery-numberformatter you could solve your problem.
Of course, this is assuming that you don't have problem with using jQuery in your project. Please notice that the functionality is tied to the blur event.
$("#salary").blur(function(){
$(this).parseNumber({format:"#,###.00", locale:"us"});
$(this).formatNumber({format:"#,###.00", locale:"us"});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/timdown/jshashtable/hashtable.js"></script>
<script src="https://cdn.jsdelivr.net/gh/hardhub/jquery-numberformatter/src/jquery.numberformatter.js"></script>
<input type="text" id="salary">
You may want to consider using toLocaleString()
Working Example:
const number = 1234567890.123;
console.log(number.toLocaleString('en-US')); // US format
console.log(number.toLocaleString('en-IN')); // Indian format
Tested in Chrome v60 and v88
Source: Number.prototype.toLocaleString() | MDN
function numberWithCommas(x) {
x=String(x).toString();
var afterPoint = '';
if(x.indexOf('.') > 0)
afterPoint = x.substring(x.indexOf('.'),x.length);
x = Math.floor(x);
x=x.toString();
var lastThree = x.substring(x.length-3);
var otherNumbers = x.substring(0,x.length-3);
if(otherNumbers != '')
lastThree = ',' + lastThree;
return otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
}
console.log(numberWithCommas(100000));
console.log(numberWithCommas(10000000));
Output
1,00,000
1,00,00,000
This is an article about your problem. Adding a thousands-seperator is not built in to JavaScript, so you'll have to write your own function like this (example taken from the linked page):
function addSeperator(nStr){
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Or you could use the sugar.js library, and the format method:
format( place = 0 , thousands = ',' , decimal = '.' ) Formats the number to a readable string. If place is undefined, will automatically
determine the place. thousands is the character used for the thousands
separator. decimal is the character used for the decimal point.
Examples:
(56782).format() > "56,782"
(56782).format(2) > "56,782.00"
(4388.43).format(2, ' ') > "4 388.43"
(4388.43).format(3, '.', ',') > "4.388,430"
Let me also throw my solution in here. I've commented each line for ease of reading and also provided some examples, so it may look big.
function format(number) {
var decimalSeparator = ".";
var thousandSeparator = ",";
// make sure we have a string
var result = String(number);
// split the number in the integer and decimals, if any
var parts = result.split(decimalSeparator);
// if we don't have decimals, add .00
if (!parts[1]) {
parts[1] = "00";
}
// reverse the string (1719 becomes 9171)
result = parts[0].split("").reverse().join("");
// add thousand separator each 3 characters, except at the end of the string
result = result.replace(/(\d{3}(?!$))/g, "$1" + thousandSeparator);
// reverse back the integer and replace the original integer
parts[0] = result.split("").reverse().join("");
// recombine integer with decimals
return parts.join(decimalSeparator);
}
document.write("10 => " + format(10) + "<br/>");
document.write("100 => " + format(100) + "<br/>");
document.write("1000 => " + format(1000) + "<br/>");
document.write("10000 => " + format(10000) + "<br/>");
document.write("100000 => " + format(100000) + "<br/>");
document.write("100000.22 => " + format(100000.22) + "<br/>");
This will get you your comma seperated values as well as add the fixed notation to the end.
nStr="1000";
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
commaSeperated = x1 + x2 + ".00";
alert(commaSeperated);
Source
If you're using jQuery, you could use the format or number format plugins.
function formatNumber1(number) {
var comma = ',',
string = Math.max(0, number).toFixed(0),
length = string.length,
end = /^\d{4,}$/.test(string) ? length % 3 : 0;
return (end ? string.slice(0, end) + comma : '') + string.slice(end).replace(/(\d{3})(?=\d)/g, '$1' + comma);
}
function formatNumber2(number) {
return Math.max(0, number).toFixed(0).replace(/(?=(?:\d{3})+$)(?!^)/g, ',');
}
Source: http://jsperf.com/number-format
This is about 3 times faster version of the accepted answer. It doesn't create array and avoids object creation and string concatenation for whole numbers at the end. This might be useful if you render lots of values e.g. in a table.
function addThousandSeparators(number) {
var whole, fraction
var decIndex = number.lastIndexOf('.')
if (decIndex > 0) {
whole = number.substr(0, decIndex)
fraction = number.substr(decIndex)
} else {
whole = number
}
var rgx = /(\d+)(\d{3})/
while (rgx.test(whole)) {
whole = whole.replace(rgx, '$1' + ',' + '$2')
}
return fraction ? whole + fraction : whole
}
function formatThousands(n,dp,f) {
// dp - decimal places
// f - format >> 'us', 'eu'
if (n == 0) {
if(f == 'eu') {
return "0," + "0".repeat(dp);
}
return "0." + "0".repeat(dp);
}
/* round to 2 decimal places */
//n = Math.round( n * 100 ) / 100;
var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
while ( (i -= 3) > 0 ) { r = ',' + s.substr(i, 3) + r; }
var a = s.substr(0, i + 3) + r + (d ? '.' + Math.round((d+1) * Math.pow(10,dp)).toString().substr(1,dp) : '');
/* change format from 20,000.00 to 20.000,00 */
if (f == 'eu') {
var b = a.toString().replace(".", "#");
b = b.replace(",", ".");
return b.replace("#", ",");
}
return a;
}

Categories

Resources