Adding commas, decimal to number output javascript - javascript

I'm using the following code to count up from a starting number. What I need is to insert commas in the appropriate places (thousands) and put a decimal point in front of the last two digits.
function createCounter(elementId,start,end,totalTime,callback)
{
var jTarget=jQuery("#"+elementId);
var interval=totalTime/(end-start);
var intervalId;
var current=start;
var f=function(){
jTarget.text(current);
if(current==end)
{
clearInterval(intervalId);
if(callback)
{
callback();
}
}
++current;
}
intervalId=setInterval(f,interval);
f();
}
jQuery(document).ready(function(){
createCounter("counter",12714086+'',9999999999,10000000000000,function(){
alert("finished")
})
})
Executed here: http://jsfiddle.net/blackessej/TT8BH/3/

var s = 121221;
Use the function insertDecimalPoints(s.toFixed(2));
and you get 1,212.21
function insertDecimalPoints(s) {
var l = s.length;
var res = ""+s[0];
console.log(res);
for (var i=1;i<l-1;i++)
{
if ((l-i)%3==0)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res = res.replace(',.','.');
return res;
}

Check out this page for explanations on slice(), split(), and substring(), as well as other String Object functions.
var num = 3874923.12 + ''; //converts to a string
numArray = num.split('.'); //numArray[0] = 3874923 | numArray[1] = 12;
commaNumber = '';
i = numArray[0].length;
do
{
//we don't want to start slicing from a negative number. The following line sets sliceStart to 0 if i < 0. Otherwise, sliceStart = i
sliceStart = (i-3 >= 0) ? i-3 : 0;
//we're slicing from the right side of numArray[0] because i = the length of the numArray[0] string.
var setOf3 = numArray[0].slice(sliceStart, i);
commaNumber = setOf3 + ',' + commaNumber; //prepend the new setOf3 in front, along with that comma you want
i -= 3; //decrement i by 3 so that the next iteration of the loop slices the next set of 3 numbers
}
while(i >= 0)
//result at this point: 3,874,923,
//remove the trailing comma
commaNumber = commaNumber.substring(0,commaNumber.length-1);
//add the decimal to the end
commaNumber += '.' + numArray[1];
//voila!

This function can be used for if not working locale somite
number =1000.234;
number=insertDecimalPoints(number.toFixed(3));
function insertDecimalPoints(s) {
console.log(s);
var temaparray = s.split(".");
s = temaparray[0];
var l = s.length;
var res = ""//+s[0];
console.log(res);
for (var i=0;i<l-1;i++)
{
if ((l-i)%3==0 && l>3)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res =res +"."+temaparray[1];
return res;
}

function convertDollar(number) {
var num =parseFloat(number);
var n = num.toFixed(2);
var q =Math.floor(num);
var z=parseFloat((num).toFixed(2)).toLocaleString();
var p=(parseFloat(n)-parseFloat(q)).toFixed(2).toString().replace("0.", ".");
return z+p;
}

Related

How do I match the numbers sequence rising?

I have a string contains just numbers. Something like this:
var numb = "5136789431235";
And I'm trying to match ascending numbers which are two or more digits. In string above I want this output:
var numb = "5136789431235";
// ^^^^ ^^^
Actually I can match a number which has two or more digits: /[0-9]{2,}/g, But I don't know how can I detect being ascending?
To match consecutive numbers like 123:
(?:(?=01|12|23|34|45|56|67|78|89)\d)+\d
RegEx Demo
To match nonconsecutive numbers like 137:
(?:(?=0[1-9]|1[2-9]|2[3-9]|3[4-9]|4[5-9]|5[6-9]|6[7-9]|7[8-9]|89)\d)+\d
RegEx Demo
Here is an example:
var numb = "5136789431235";
/* The output of consecutive version: 6789,123
The output of nonconsecutive version: 136789,1234
*/
You could do this by simply testing for
01|12|23|34|45|56|67|78|89
Regards
You just need to loop through each number and check next one. Then add that pair of values to a result variable:
var numb = "5136789431235";
var res = [];
for (var i = 0, len = numb.length; i < len-1; i++) {
if (numb[i] < numb[i+1]) res.push(new Array(numb[i],numb[i+1]))
}
res.forEach(function(k){console.log(k)});
Here is fiddle
Try this to match consecutive numbers
var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]
DEMO
var numb = "5136789431235";
var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]
document.body.innerHTML += JSON.stringify(matches,0,4);
Do you have to use Regex?
Not sure if the most efficient, but since they're always going to be numbers, could you split them up into an array of numbers, and then do an algorithm on that to sort through?
So like
var str = "123456";
var res = str.split("");
// res would equal 1,2,3,4,5,6
// Here do matching algorithm
Not sure if this is a bad way of doing it, just another option to think about
I've did something different on a fork from jquery.pwstrength.bootstrap plugin, using substring method.
https://github.com/andredurao/jquery.pwstrength.bootstrap/commit/614ddf156c2edd974da60a70d4945a1e05ff9d8d
I've created a string containing the sequence ("123456789") and scanned the sequence on a sliding window of size 3.
On each scan iteration I check for a substring of the window on the string:
var numb = "5136789431235";
//check for substring on 1st window => "123""
"5136789431235"
ˆˆˆ

Internationally pretty print string objects that contain decimals

I am using MikeMcl's big.js for precise accounting which outputs a string when calling toFixed().
I'd like to pretty print decimal results in an internationally aware way much like how the Date Object can automatically print dates and times in a local format.
Is there a way to format string objects that contain decimals internationally?
var myNumber = 123456.78;
console.log(myNumber.toLocaleString());
This should do the job.
function localize(fixed) {
/*Determine decimal symbol and digit grouping symbol.*/
var decimalSymbol = '.';
var digitGroupingSymbol = ',';
var dummy = 1234.5;
testResult = dummy.toLocaleString();
/*Browsers using digit grouping symbol.*/
if (testResult.length === 7) {
decimalSymbol = testResult[5];
digitGroupingSymbol = testResult[1];
}
/*Browsers not using digit grouping symbol.*/
if (testResult.length === 6) {
decimalSymbol = testResult[4];
digitGroupingSymbol = (decimalSymbol === '.'? ',': '.');
}
/*Format the number.*/
var result = '';
var dsIndex = fixed.indexOf('.');
if (dsIndex < 0) {
throw new Error('Expected decimal separator \'.\' in "' + fixed + '".');
}
for (var i = 0; i < dsIndex; ++i) {
if (fixed[i] < '0' || fixed[i] > '9') {
throw new Error('Expected digit, got "' + fixed[i] + '".');
}
if (i > 0 && i%3 === dsIndex%3) result += digitGroupingSymbol ;
result += fixed[i];
}
result += decimalSymbol + fixed.substr(dsIndex + 1);
return result;
}
/*Demonstration*/
var n1 = '123.4567890';
console.assert(localize(n1));
var n2 = '1234.567890';
console.log(localize(n2));
var n3 = '123456789012345678.1234567890';
console.log(localize(n3));
var n4 = '1234567890123456789.1234567890';
console.log(localize(n4));
var n5 = '12345678901234567890.1234567890';
console.log(localize(n5));
Output:
123.4567890
1.234.567890
123.456.789.012.345.678.1234567890
1.234.567.890.123.456.789.1234567890
12.345.678.901.234.567.890.1234567890

How do I remove "undefined" from the beginning of JavaScript array items?

I'm trying to generate an array of random digits, but I'm getting "undefined" at the beginning of each row. I've been searching online for a couple of hours, but haven't been able to figure it out.
The expected output should be 5 rows of 2 random digits like this:
87
57
81
80
02
but the actual output looks like this:
undefined87
undefined57
undefined81
undefined80
undefined02
This is a modified excerpt that produces the result shown above:
function NumberSet() {
// generate all the digits
this.generate = function() {
random_digits = [];
// create 5 rows of 2 random digits
for(i=0; i<5; i++) {
for(z=0; z<2; z++) {
// use .toString() in order to concatenate digits to
// the array without adding them together
random_digit = Math.floor(Math.random()*10).toString();
random_digits[i] +=random_digit;
}
}
return random_digits;
}
}
randomnumbers1 = new NumberSet();
mynums = randomnumbers1.generate();
jQuery.each(mynums, function(i, l) {
// display output in a div#nums
$('#nums').append(l + '<br>');
});
The final version won't be using this method to display the digits. I'm just trying to troubleshoot where the "undefined" is coming from.
Initialize your variables
random_digits[i] = "";
for(z=0; z<2; z++) {
random_digit = Math.floor(Math.random()*10).toString();
random_digits[i] +=random_digit;
}
Declare the variables properly with var.
var random_digit, random_digits = [];
Declare random_digit in the first for loop and assign an empty string.
Go through the inner for loop appending your random numbers, and then push() to the array back in the outer for loop.
function NumberSet() {
// generate all the digits -a meme should be attached here-
this.generate = function() {
random_digits = [];
// create 5 rows of 2 random digits
for(i=0; i<5; i++) {
var random_digit = ""; //Declare it out here
for(z=0; z<2; z++) {
// use .toString() in order to concatenate digits to
// the array without adding them together
random_digit += Math.floor(Math.random()*10).toString(); //Append it here
}
random_digits.push(random_digit); //Push it back here
}
return random_digits;
}
}
Fiddle-dee-dee
OR Forget the inner loop and use recursion
function NumberSet() {
// generate all the digits
this.generate = function () {
random_digits = [];
// create 5 rows of 2 random digits
// Use i for how many numbers you want returned!
var random_digit = function (i) {
var getRand = function() {
return (Math.floor(Math.random() * 10).toString());
}
return (i > 0) ? getRand()+random_digit(i-1) : "";
};
for (i = 0; i < 5; i++) {
random_digits.push(random_digit(2)); //In this case, you want 2 numbers
}
return random_digits;
}
}
Fiddle-do-do
And the final version because I'm bored
function NumberSet(elNum, numLen) {
this.random_digits = []; //Random digits array
this.elNum = elNum; //Number of elements to add to the array
this.numLen = numLen; //Length of each element in the array
// generate all the digits
this.generate = function () {
// create 5 rows of 2 random digits
var random_digit = function (i) {
var getRand = function () {
return (Math.floor(Math.random() * 10).toString());
}
return (i > 0) ? getRand() + random_digit(i - 1) : "";
};
for (i = 0; i < this.elNum; i++) {
this.random_digits.push(random_digit(this.numLen));
}
return this.random_digits;
}
}
randomnumbers1 = new NumberSet(5, 2).generate();
jQuery.each(randomnumbers1, function (i, l) {
// display output in a div#nums
$('#nums').append(l + '<br>');
});
Fiddle on the roof
Replace
random_digits[i] +=random_digit;
With
random_digits[i] = (random_digits[i] == undefined ? '' : random_digits[i]) + random_digit;
Demo: Fiddle
Your function can be simplified to:
function NumberSet() {
this.generate = function() {
var random_digits = new Array();
for (i = 0; i < 5; i++) {
randnum = Math.floor(Math.random() * 99);
random_digits[i] = (randnum < 10 ? '0' : 0) + randnum;
}
return random_digits;
}
}
Live Demo

Highlighting string at multiple occurrences

I'm currently implementing a substring search. From the algorithm, I get array of substrings occurence positions where each element is in the form of [startPos, endPos].
For example (in javascript array):
[[1,3], [8,10], [15,18]]
And the string to highlight is:
ACGATCGATCGGATCGAGCGATCGAGCGATCGAT
I want to highlight (in HTML using <b>) the original string, so it will highlight or bold the string from position 1 to 3, then 8 to 10, then 15 to 18, etc (0-indexed).
A<b>CGA</b>TCGA<b>TCG</b>GATC<b>GAGC</b>GATCGAGCGATCGAT
This is what I have tried (JavaScript):
function hilightAtPositions(text, posArray) {
var startPos, endPos;
var startTag = "<b>";
var endTag = "</b>";
var hilightedText = "";
for (var i = 0; i < posArray.length; i++) {
startPos = posArray[i][0];
endPos = posArray[i][1];
hilightedText = [text.slice(0, startPos), startTag, text.slice(startPos, endPos), endTag, text.slice(endPos)].join('');
}
return hilightedText;
}
But it highlights just a range from the posArray (and I know it is still incorrect yet). So, how can I highlight a string given multiple occurrences position?
Looking at this question, and following John3136's suggestion of going from tail to head, you could do:
String.prototype.splice = function( idx, rem, s ) {
return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem)));
};
function hilightAtPositions(text, posArray) {
var startPos, endPos;
posArray = posArray.sort(function(a,b){ return a[0] - b[0];});
for (var i = posArray.length-1; i >= 0; i--) {
startPos = posArray[i][0];
endPos = posArray[i][1];
text= text.splice(endPos, 0, "</b>");
text= text.splice(startPos, 0, "<b>");
}
return text;
}
Note that in your code, you are overwriting hilightedText with each iteration, losing your changes.
Try this:
var stringToHighlight = "ACGATCGATCGGATCGAGCGATCGAGCGATCGAT";
var highlightPositions = [[1,3], [8,10], [15,18]];
var lengthDelta = 0;
for (var highlight in highlightPositions) {
var start = highlightPositions[highlight][0] + lengthDelta;
var end = highlightPositions[highlight][1] + lengthDelta;
var first = stringToHighlight.substring(0, start);
var second = stringToHighlight.substring(start, end + 1);
var third = stringToHighlight.substring(end + 1);
stringToHighlight = first + "<b>" + second + "</b>" + third;
lengthDelta += ("<b></b>").length;
}
alert(stringToHighlight);
Demo: http://jsfiddle.net/kPkk3/
Assuming that you're trying to highlight search terms or something like that. Why not replace the term with the bolding?
example:
term: abc
var text = 'abcdefgabcqq';
var term = 'abc';
text.replace(term, '<b>' + term + '</b>');
This would allow you to avoid worrying about positions, assuming that you are trying to highlight a specific string.
Assuming your list of segments is ordered from lowest start to highest, try doing your array from last to first.
That way you are not changing parts of the string you haven't reached yet.
Just change the loop to:
for (var i = posArray.length-1; i >=0; i--) {
If you want to check for multiple string matches and highlight them, this code snippet works.
function highlightMatch(text, matchString) {
let textArr = text.split(' ');
let returnArr = [];
for(let i=0; i<textArr.length; i++) {
let subStrMatch = textArr[i].toLowerCase().indexOf(matchString.toLowerCase());
if(subStrMatch !== -1) {
let subStr = textArr[i].split('');
let subStrReturn = [];
for(let j=0 ;j<subStr.length; j++) {
if(j === subStrMatch) {
subStrReturn.push('<strong>' + subStr[j]);
} else if (j === subStrMatch + (matchString.length-1)){
subStrReturn.push(subStr[j] + '<strong>');
} else {
subStrReturn.push(subStr[j]);
}
}
returnArr.push(subStrReturn.join(''));
} else {
returnArr.push(textArr[i]);
}
}
return returnArr;
}
highlightMatch('Multi Test returns multiple results', 'multi');
=> (5) ['<strong>Multi<strong>', 'Test', 'returns', '<strong>multi<strong>ple', 'results']

how to get formatted integer value in javascript

This is my integer value
12232445
and i need to get like this.
12,232,445
Using prototype how to get this?
var number = 12232445,
value = number.toString(),
parts = new Array;
while (value.length) {
parts.unshift(value.substr(-3));
value = value.substr(0, value.length - 3);
}
number = parts.join(',');
alert(number); // 12,232,445
It might not be the cleanest solution, but it'll do:
function addCommas(n)
{
var str = String(n);
var result = '';
for(var i = 0; i < str.length; i++)
{
if((i - str.length) % 3 == 0)
result += ',';
result += str[i];
}
return result;
}
Here is the function I use, to format thousands separators and takes into account decimals if any:
function thousands(s) {
var rx = /(-?\d+)(\d{3})/,
intDec = (''+s)
.replace(new RegExp('\\' + $b.localisation.thousandSeparator,'g'), '')
.split('\\' + $b.user.localisation.decimalFormat),
intPart = intDec[0],
decPart = intDec[1] || '';
while (rx.test(intPart)) {
intPart = intPart.replace(rx,'$1'+$b.localisation.thousandSeparator+'$2');
}
return intPart + (decPart && $b.localisation.decimalFormat) + decPart;
}
thousands(1234.56) //--> 1,234.56
$b.localisation is a global variable used for the session.
$b.localisation.thousands can have the values , or . or a space.
And $b.localisation.decimalFormat can have the values , or . depending on the locale of the user

Categories