How can I have comma separators displayed in the calculation results?
(123456789 to show as 123,456,789)
function calculate(){
a=Number(document.calculator.number1.value);
b=Number(document.calculator.number2.value);
A1=a*2000
document.calculator.totalA1.value=A1;
A2=a*b*240
document.calculator.totalA2.value=A2;
A3=a*8*240
document.calculator.totalA3.value=A3;
A4=a*960*5
document.calculator.totalA4.value=A4;
A5=a*3600*5
document.calculator.totalA5.value=A5;
A6=a*3000
document.calculator.totalA6.value=A6;
A7=A1+A2+A3+A4+A5+A6
document.calculator.totalA7.value=A7;
A8=a*120000
document.calculator.totalA8.value=A8;
A9=A8-A7
document.calculator.totalA9.value=A9;
}
I've seen many suggestions but don't know where to insert the script.
Thanks!
You could try something like this using RegExp
$("#button").click(function(){
var a = 100;
var A1=(a*2000);
alert(String(A1).replace(/(\d{3})(?!$)/g, "$1,"));
})
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<button type="button" id="button">Calculate </button>
Here you go: https://jsfiddle.net/odewuqun/3/
function addPunctuation(number){
var array = number.toString().split("");
var output = "";
var first = true;
for(var i = array.length-1; i >= 0; i--){
if((array.length-i-1) % 3 === 0){
if(first){
first = false;
}else{
output = "," + output;
}
}
output = array[i] + output;
}
return output;
}
Short explanation:
Convert the number into a String.
Split that String into an array.
Iterate over that array from the end and make a new String where you add a , between every 3 chars.
That is archieved by index % 3 === 0. (% is the mathematic modulo operator for whole number division with rest)
Related
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"
ˆˆˆ
If the field is left blank, it will return NaN as the average. How can I get this to return 0 instead?
This is what I have for my HTML file:
<html>
<head>
<title> Average Numbers </title>
<script type="text/javascript" src="arrays.js"></script>
<script type="text/javascript">
function ShowAvg()
// Assumes: numsBox contains a sequence of numbers
// Results: displays the average of the numbers in outputDiv
{
var str, strArray, numArray;
str = document.getElementById('numsBox').value;
if ( isNan(str)){
document.getElementById('numArray').value = '0';
}
strArray = str.split(/[, \t\n]+/); // SPLIT STRING INTO AN ARRAY
numArray = ParseArray(strArray); // STORE ARRAY VALUES AS NUMS4
document.getElementById('outputDiv').innerHTML =
'The average of [' + numArray + '] is ' + Average(numArray);
}
</script>
</head>
<body>
<p>
Enter numbers: <input type="text" id="numsBox" size=40 value="">
</p>
<p>
<input type="button" value="Compute the Average" onclick="ShowAvg();">
</p>
<div id="outputDiv"></div>
</body>
</html>
This is my javascript file:
function Acronym(phrase)
// Assumes: phrase is a string of words, separated by whitespace
// Returns: the acronym made up of first letters from the words
{
var words, acronym, index, nextWord;
words = phrase.split(/[ \t\n]+/); // CONVERT phrase TO AN ARRAY
acronym = ''; // INITIALIZE THE acronym
index = 0; // START AT FIRST WORD
while (index < words.length) { // AS LONG AS WORDS LEFT
nextWord = words[index]; // GET NEXT WORD
acronym = acronym + nextWord.charAt(0); // ADD FIRST CHAR OF WORD
index = index + 1; // GO ON TO NEXT WORD
}
return acronym.toUpperCase(); // RETURN UPPER CASE acronym
}
function ParseArray(strArray)
// Assumes: strArray is an array of strings representing numbers
// Returns: a copy of strArray with items converted to numbers
{
var numArray, index;
numArray = [ ]; // CREATE EMPTY ARRAY TO STORE COPY
index = 0; // FOR EACH ITEM IN strArray
while (index < strArray.length) { // CONVERT TO NUMBER AND COPY
numArray[index] = parseFloat(strArray[index]);
index = index + 1;
}
return numArray; // FINALLY, RETURN THE COPY
}
function Average(numArray)
// Assumes: numArray is an array of numbers
// Returns: average of the numbers in numArray
{
var sum, index;
sum = 0; // INITIALIZE sum
index = 0; // START AT FIRST NUMBER
while (index < numArray.length) { // AS LONG AS NUMBERS LEFT
sum = sum + numArray[index]; // ADD NUMBER TO sum
index = index + 1; // GO ON TO NEXT NUMBER
}
return sum/numArray.length; // RETURN AVERAGE
}
Thanks in advance for any and all help. I'm a noob at this and have been struggling for hours trying to figure this out.
to make a long story short, just add
value = value || 0;
for a default value.
I got following problems
isNan() should be isNaN()
document.getElementById('numArray').value = '0'; is not working, because its a button, not an input field, Use instead document.getElementById('numsBox').value = '0';.
Longer answer: In your js file, replace
return numArray;
}
with
avgNum = sum/numArray.length;
if (avgNum != avgNum) {
avgNum = 0;
}
return avgNum; // RETURN AVERAGE
}
You will still need to change the str NaN display in the html file (I would just take it out and say the average is: since the numbers are still shown at the top). The reason this works is that the only this NaN is not equal to is itself (which is sooo weird). Code On!
Currently output 1844.6304
desired output - comma thousands trim after dot ( no rounding )
1,844
I was looking some time on forums and can't find a solution to solve both cases.
Try this:
function intWithCommas(x) {
return Math.floor(x).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Example:
> intWithCommas(1844.6304)
'1,844'
Its even simpler like this
var n = 1844.6304,
s = Math.floor(n).toLocaleString();
console.log(s); //"1,844"
alert(s);
Try this:
function toCommaInteger(number){
var result = "" + ~~number;
var length = result.length;
var limit = result[0] === "-" ? 1 : 0;
for(var i = length-3; i > limit; i-=3 ){
result = result.substring(0,i) + "," + result.substring(i,length);
length++;
}
return result;
}
toCommaInteger(123589.85315) => 123,589
toCommaInteger(-1289.15315) => -1,289
toCommaInteger(5) => 5
I'm sorry it's a stupid question but I'm try to list a sequence of numbers from 1 to a limit and they should be separated by comma. I have a problem. I don't know how to stop the comma. I should have 1,2,3 but I have ,1,2,3. Can you help me? Here is my code.
function getNumberSequence(number) {
var result = ""
if(number <= 0){
return result
}
else{
if(number == 1){
result = result + 1
} else {
for(i = 1; i <= number; i++){
result = result + ',' + i;
}
}
}
return result
}
Thanks for all
You can simply add a flag (in the example "first") and check if this is your first iteration - if so, don't add a comma but set it to false ... see here: http://jsfiddle.net/fdfxc5zq/
var first = true; //have a flag that tells you if this is your first iteration - don't add a comma the first time around
for (i = 0; i <= number; i++) {
if (first) {
first = false;
} else {
result += ", ";
}
result += i;
}
Using your code, simply declare result with an initial value of 1 and start the for loop with i=2. Solved. (And in case of number being 1, just return result)
A one-liner for you:
return Object.keys(Array.apply(null,new Array(number))).map(function(n) {return +n+1;}).join(",");
Basically, creates an array of length number, "applies" it (basically ends up giving undefined values to each index), then uses Object.keys to get the indices of the array, increments all the items, then joins the whole thing with commas.
Two easy methods:
1) Just add a comma after each number and return a substring of length-1 to get rid of the last comma
if (i === 0) return ""; //to avoid substring() issues on empty strings
var result = "";
for (i = 0; i <= number; i++) {
result = i + ",";
}
return result.substr(0, result.length-1);
2) Using array and join
var result = [];
for (i = 0; i <= number; i++) {
result.push(i)
}
return result.join(); //default join separator is the comma
YourCommaSeparatedString.split(',');
I have a number in JavaScript that I'd like to convert to a money format:
556633 -> £5566.33
How do I do this in JavaScript?
Try this:
var num = 10;
var result = num.toFixed(2); // result will equal string "10.00"
This works:
var currencyString = "£" + (amount/100).toFixed(2);
Try
"£"+556633/100
This script making only integer to decimal.
Seperate the thousands
onclick='alert(MakeDecimal(123456789));'
function MakeDecimal(Number) {
Number = Number + "" // Convert Number to string if not
Number = Number.split('').reverse().join(''); //Reverse string
var Result = "";
for (i = 0; i <= Number.length; i += 3) {
Result = Result + Number.substring(i, i + 3) + ".";
}
Result = Result.split('').reverse().join(''); //Reverse again
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
return Result;
}
Using template literals you can achieve this:
const num = 556633;
const formattedNum = `${num/100}.00`;
console.log(formattedNum);