I have the following JavaScript code which is writing in a HTML form:
<script type="text/javascript">
function updatesum() {
document.functie.column8.value = (document.functie.column6.value -0) * (document.functie.column7.value -0);
document.functie.column12.value = (document.functie.column10.value -0) * (document.functie.column11.value -0);
document.functie.column16.value = (document.functie.column14.value -0) * (document.functie.column15.value -0);
document.functie.column20.value = (document.functie.column18.value -0) * (document.functie.column19.value -0);
}
and with the php form like:
echo "<td><input name=\"column6\" onChange=\"updatesum()\"></td>";
echo "<td><input name=\"column7\" onChange=\"updatesum()\"></td>";
The problem is that when I put some values in the first form, it gives me the sum, but if I don't put some values it gives me zero, which I do not want:
http://img17.imageshack.us/img17/5456/hyhu.png http://img17.imageshack.us/img17/5456/hyhu.png
In the bottom I have a sum of all the values from the 3rd column, but the it gives me numbers like 2400 or 2300.44, and I want an output of 2,400 or to roundup the 2300.44 to 2,300. How can I do that?
1/ You're multiplying with a value '' automatically cast to an integer, so 0. This is normal that you end up with 0. If you do not want that, you'll have to create a function that check the value of the inputs and return '' if one of them is ''
something like:
function multiply(v1, v2) {
if (v1 === '' || v2 === '' || isNaN(v1) || isNaN(v2)) {
return '';
}
return v1*v2;
}
2/ You'll need to add a format function, that will format your code and add the , where it must and get ride of the decimals (or use links in that comment javascript updatesum() problems) :
function formatNumber(num) {
var formatted = '';
num = Math.ceil(num) + '';
for (var i = num.length - 1, j = 0; c = num.charAt(i); i--) {
if (j % 3 === 0) {
c = c + ',';
}
formatted = c + formatted;
j++;
}
return formatted.trim();
}
You asked for an example. This should do it in place of your current updatesum function:
function multiply(v1, v2) {
if (v1 === '' || v2 === '' || isNaN(v1) || isNaN(v2)) {
return '';
}
return v1*v2;
}
function multiplyAndFormat(v1, v2) {
return formatNumber(multiply(v1, v2));
}
function formatNumber(num) {
var formatted = '';
num = Math.ceil(num) + '';
for (var i = num.length - 1, j = 0; c = num.charAt(i); i--) {
if (j % 3 === 0) {
c = c + ',';
}
formatted = c + formatted;
j++;
}
return formatted.trim();
}
function updatesum() {
document.functie.column8.value = multiplyAndFormat(document.functie.column6.value, document.functie.column7.value);
document.functie.column12.value = multiplyAndFormat(document.functie.column10.value, document.functie.column11.value);
document.functie.column16.value = multiplyAndFormat(document.functie.column14.value, document.functie.column15.value);
document.functie.column20.value = multiplyAndFormat(document.functie.column18.value, document.functie.column19.value);
}
should do it
Related
I am trying to insert dashes ('-') between each two odd numbers and insert asterisks ('*') between each two even numbers, but I am only getting the last result.
I want to print out all the elements in the array.
For example: if num is 4546793 the output should be 454*67-9-3. I Did not count zero as an odd or even number.
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
if (num[i] === 0) {
continue;
}
if (num[i - 1] % 2 == 0 && num[i] % 2 == 0) {
result = num[i - 1] + "*" + num[i];
continue;
}
if (num[i - 1] % 2 == !0 && num[i] % 2 == !0) {
result = num[i - 1] + "-" + num[i];
continue;
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
You do not need to check as if&continue. Inserting given numbers to the result string and only adding "-" when index and previous are odd, and "*" when index and previous are even.
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
if (num[i]%2 ===0) {// even
if(i !== 0 && num[i-1]%2===0){// previous is even either
result+="*"+num[i];
}else{
result+=num[i];
}
}else{// odd
if(i !== 0 && num[i-1]%2===1){// previous is odd either
result+="-"+num[i];
}else{
result+=num[i];
}
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
Try this :)
function test(a){
let result=""
for(let i=0; i < a.length; i++){
if(a[i] != 0 && a[i-1] % 2 == 0 && a[i] % 2 == 0){
result = result + '*' + a[i]
}
else if (a[i] != 0 && a[i-1] % 2 != 0 && a[i] % 2 != 0){
result = result + '-' + a[i]
}
else{
result = result + a[i]
}
}
return result
}
console.log(test([4,5,4,6,7,9,3]));
As everyone has identified, the problem is you are not adding to result.
But here is a suggestion to make your code easier to read
// These one line functions make your code easier to read
function IsEven(num){
return num % 2 === 0;
}
function IsOdd(num){
return num % 2 !== 0;
}
function StringChallenge(numArray) {
// return empty string if not an array or empty array
if(!Array.isArray(numArray) || numArray.length === 0) return "";
let result = "" + numArray[0]; // use "" to coerce first element of numArray from number to string
for (let i = 1; i < numArray.length; i++) {
// focus on the conditions to determine the separator you want between each element
separator = "";
if (numArray[i] !== 0) {
if (IsEven(numArray[i]) && IsEven(numArray[i - 1])) {
separator = "*";
} else if (IsOdd(numArray[i]) && IsOdd(numArray[i - 1])){
separator = "-";
}
}
// build the result
result += separator + numArray[i];
}
return result;
}
I will do that this way :
== some advices for 2 cents ==
1 - try to make your code as readable as possible.
2 - use boolean tests rather than calculations to simply do a parity test
3 - ES7 has greatly improved the writing of JS code, so take advantage of it
console.log(StringChallenge([4,5,4,6,7,9,3])); // 454*67-9-3
function StringChallenge( Nums = [] )
{
const
isOdd = x => !!(x & 1) // Boolean test on binary value
, isEven = x => !(x & 1) && x!==0 // zero is not accepted as Even value
;
let result = `${Nums[0]??''}`; // get first number as
// result if Nums.length > 0
for (let i=1; i<Nums.length; i++)
{
if ( isOdd(Nums[i-1]) && isOdd(Nums[i]) ) result += '-';
if ( isEven(Nums[i-1]) && isEven(Nums[i]) ) result += '*';
result += `${Nums[i]}`; // same as Nums[i].toString(10);
}
return result
}
I hope this helps. I tried to keep it as simple as possible.
function StringChallenge(num) {
//start with a string to concatenate, or else interpreter tries to do math
operations
let result = num[0].toString();
function checkOdd(num){ //helper function to check if odd
return num % 2
}
for (let i = 0; i < num.length - 1; i++) {
if (checkOdd(num[i]) && checkOdd(num[i+1])) { //checks if both odd
result += `-${num[i+1]}`; //adds - and next number
} else if (!checkOdd(num[i]) && !checkOdd(num[i+1])) { //checks if both even
result += `*${num[i+1]}`; //adds * and next number
} else { //otherwise
result += num[i+1]; //just add next number
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
Use +=. And, change your logic, your code prints out "4*67-99-3".
The zero check was pretty hard for me I hope the variables in my code explain itself. If not, let me know.
function even(num) {
return num % 2 === 0;
}
function odd(num) {
return num % 2 !== 0;
}
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
var currentZero = num[i] === 0
var previousZero = num[i-1] === 0
var bothEven = even(num[i]) && even(num[i-1])
var bothOdd = odd(num[i]) && odd(num[i-1])
var firstNumber = (i === 0)
if (!currentZero) {
if (firstNumber) {
result += num[i]
} else {
if (bothEven && !previousZero) {
result += "*" + num[i]
} else if (bothOdd && !currentZero) {
result += "-" + num[i]
} else {
result += num[i]
}
}
}
}
return result;
}
console.log(StringChallenge([0,4,5,0,4,6,7,9,3]));
I am working on a requirement where I want to do some calculation on the numbers entered in the dxtextbox,
For example if I am entering:
123456789
then the calculation will be like
num1=1 *3;num2=2 *7;num3=3 ;num4=4 *3;num5=5 *7;num6=6;num7=7 *3;num8=8*7;num9=9;
sum=num1+num2+num3+num4+num5+num6+num7+num8+num9
if(sum != 0 && sum % 10 == 0){it will return true}else it should return false
I searched this in your documentation section but didn't got any thing.
Can you please help me to solve this requirement .
I have attached a sample solution where you can see the kind of validation structure I trying to accomplish this task.
Thank You
$(document).ready(function()
{
var enteredNumber = 123456789;
var numTotal = 0;
var multiplikator = Array(3,7,1);
var multiplikatorCnt = 0;
for(a=0;a < enteredNumber.toString().length; a++)
{
numTotal += parseInt((enteredNumber.toString())[a]) * multiplikator[multiplikatorCnt];
multiplikatorCnt++;
if(multiplikatorCnt > 2)
{
multiplikatorCnt = 0;
}
}
if(numTotal != 0 && numTotal % 10 == 0)
{
return true
}
else
{
return false
}
});
Edit: forgot to return true or false.
Shorter would be:
$(document).ready(function()
{
var enteredNumber = 123456789;
var numTotal = 0;
var multiplikator = Array(3,7,1);
for(a=0;a < enteredNumber.toString().length; a++)
{
numTotal += parseInt((enteredNumber.toString())[a]) * multiplikator[a % multiplikator.length];
}
if(numTotal != 0 && numTotal % 10 == 0)
{
return true
}
else
{
return false
}
});
Thank You for your quick response,I am able to solve it by my self
here is the code what I am using
var valuenum = $("#txt_value").dxTextBox("instance");
var checknumber = valuenum .option('value');
var arr = checknumber.split('');
var num1, num2, num3, num4;
num1 = (arr[0]) * 3;
num2 = (arr[1]) * 7;
num3 = (arr[2]);
num4 = (arr[3]) * 3;
var totalval = parseInt(num1) + parseInt(num2) + parseInt(num3) + parseInt(num4) ;
if (totalval != 0 && totalval % 10 == 0) {
return true;
}
I am learning js now..
I am trying to write a simple js programme..
what I am trying to do is to print all valid combinations of n-pair
of parenthesis(properly opened and closed)
eg (), (()()),(())
i have written the logic can you tell me whether its correct or not
https://jsfiddle.net/e7mcp6xb/
module.exports = Parentheses = (function() {
var _isParenthesesMatch = function(str) {
var parentheses = str.length;
var rightParentheses = '(';
var leftParentheses = ')';
var rightCount = 0;
var leftCount = 0;
for(i=0;i<=str.length;i++){
if(rightParentheses == str.charAt(i))
{
rightCount++;
}
else if(leftParentheses == str.charAt(i))
{
leftCount++;
}
}
if(rightCount == leftCount){
return true;
}
else(rightCount != leftCount){
return false;
}
}
}());
The check is wrong, but You can fix it easily: In each step of the for loop the number of opening parenthesis cannot be smaller than the number of closing ones:
if (rightCount < leftCount)
return false;
The whole function should look like this:
function(str) {
var rightParentheses = '(';
var leftParentheses = ')';
var rightCount = 0;
var leftCount = 0;
for (var i = 0; i <= str.length; i++) {
if (rightParentheses == str.charAt(i))
rightCount++;
else if (leftParentheses == str.charAt(i))
leftCount++;
if (rightCount < leftCount)
return false;
}
return rightCount == leftCount;
}
If You'd like to generate all valid strings, you can use this function:
function nPair(n) {
if (n == 0)
return [""];
var result = [];
for (var i = 0; i < n; ++i) {
var lefts = nPair(i);
var rights = nPair(n - i - 1);
for (var l = 0; l < lefts.length; ++l)
for (var r = 0; r < rights.length; ++r)
result.push("(" + lefts[l] + ")" + rights[r]);
}
return result;
}
// result of nPair(3):
// ["()()()", "()(())", "(())()", "(()())", "((()))"]
Try this, i have modified your code a little bit. Modification and its explanation is marked in comments.
module.exports = Parentheses = (function() {
var _isParenthesesMatch = function(str) {
var parentheses = str.length;
var rightParentheses = '(';
var leftParentheses = ')';
var count=0;
for(i=0;i<str.length;i++){
//this is to check valid combination start always from ( and end with )
if(str.charAt(0)==rightParentheses && str.length-1==leftParentheses)
{
if(rightParentheses == str.charAt(i))
{
count++; //this will calculate how many times rightParentheses is present & increment count by 1
}
else if(leftParentheses == str.charAt(i))
{
count--; //this will simply decrement count to match valid sequence
}
}
if(count==0){
return true;
}
}
}());
Your function is wrong, try checking if left and right parenthesis and balanced:
function isValid(str){
var stripedStr = str.replace(/[^\(\)]+/g, '');
return stripedStr.split('').reduce(function(a, b){
return a > -1 ? b === '(' ? a + 1 : a - 1 : -1;
}, 0) === 0;
}
stripedStr - use replace() to remove any characters that are not ( or ).
split('') - returns an array so we can use reduce.
reduce() - applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.
The reduce starts with 0 as initial value and in the reduce function we count parenthesis
(+1 for (, -1 for ) )
Our string is valid if our counter never goes below 0 and we end up with 0.
You can write the reduce function like this too:
function(previousValue, currentValue){
if (previousValue > -1){
if (currentValue === '('){
return previousValue + 1;
} else {
return previousValue - 1;
}
}
return -1;
}
This is equivalent to:
function(a, b){
return a > -1 ? b === '(' ? a + 1 : a - 1 : -1;
}
It is wrong, because your function will return true for this example ))(( or this ())(()
Here I have a function that should take a number n into the disHappy(n) to check if all
n in [n-0) are happy.
Happy Numbers wikipedia
If I only run happyChecker(n), I can tell that 7 is happy, but disHappy(n) doesn't show it. It is as if it doesn't receive the true. I have used console.log()'s all over the place and happyChecker(n) shows a number that SHOULD return true. When I placed a console.log() above the return true; for if(newNum===1), it showed that it branched into that branch but it just didn't seem to return the true.
function happyChecker(n) {
var arr = [];
var newNum = 0;
//here I split a number into a string then into an array of strings//
num = n.toString().split("");
for (var i = 0; i < num.length; i++) {
arr[i] = parseInt(num[i], 10);
}
//here I square each number then add it to newNum//
for (var i = 0; i < arr.length; i++) {
newNum += Math.pow(arr[i], 2);
}
//here I noticed that all unhappy numbers eventually came into one of these three//
//( and more) numbers, so I chose them to shorten the checking. A temporary solution for sure//
if (newNum === 58 || newNum === 4 || newNum == 37) {
return false;
}
if (newNum === 1) {
return true;
} else {
happyChecker(newNum);
}
}
function disHappy(num) {
for (j = num; j > 0; j--) {
if (happyChecker(j)) {
console.log(j + " is a Happy Number. It's so happy!!!.");
}
}
}
When you recurse, you need to return the value returned:
if (newNum === 1) {
return true;
} else {
return happyChecker(newNum);
}
You also should declare "num" with var.
I'm ordinarily not a "code golfer", but this is a good example of how the (new-ish) iterator utility methods on the Array prototype can clean up code. You can use the .reduce() function to traverse the array of digit characters and do the work of squaring and summing all at once:
var newNum = n.toString()
.split('')
.reduce(function(sum, digit) {
return sum + (+digit * +digit);
}, 0);
The call to .toString() returns a string, then .split('') gives you an array. Then .reduce() starts with an initial sum of 0 and for each element of the array (each digit), it adds to it the square of that digit. (Instead of parseInt() I just used the + unary operator; we know for sure that each string will be a valid number and an integer.)
You need to add return to the happyChecker call.
return happyChecker(newNum);
see:
http://jsfiddle.net/YjgL8/2/
here is my implementation
var getSum = function (n) {
if (!n >= 0) return -1;
var digits = n.toString().split("");
var sum = 0;
for (var i = 0; i < digits.length; i++) {
var digit = parseInt(digits[i], 10);
sum += digit * digit;
}
return sum;
}
/**
* #param {number} n
* #return {boolean}
*/
var isHappy = function(n, visited) {
if (n < 0) return false;
if (n === 1) return true;
if (typeof visited === 'undefined') visited = {};
sum = getSum(n);
if (visited[sum]) return false; // cycle
visited[sum] = true;
return isHappy(sum, visited);
};
Complete Example of finding happy numbers in range of custom number.
function happyNumbers() {
var result = document.getElementById("happy-result")
var inputy = parseInt(document.getElementById("happyValue").value)
result.innerHTML=""
for (i = 1; i < inputy; i++) {
(happy(i, i))
}
}
function happy(value,value2) {
var result = document.getElementById("happy-result")
var lengthNum = value.toString().length;
var resultNumbers = 0
for (var b = 0 ; b < lengthNum; b++) {
resultNumbers = resultNumbers + parseInt(value.toString().charAt(b)) * parseInt(value.toString().charAt(b))
}
if (resultNumbers == 4) {
return false
} else if (resultNumbers == 1) {
result.innerHTML += "<br> happy number " + i
return true
}else{
happy(resultNumbers, value2);
}
}
window.onload=happyNumbers()
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="panel panel-default">
<div class="panel-heading">happy numbers</div>
<div class="panel-body">
<label>Enter the number that you want ot have see happy numbers uo to it</label>
<input id="happyValue" oninput="happyNumbers()" value="100" class="form-control" />
<div id="happy-result"></div>
</div>
</div>
When adding Javascript to a PDF, is it possible for me to print a float so that it looks like this: $50,0000?
I don't care about internationalization.
I can use util.printf, but it won't put the commas in.
Did you mean to do it by javascript. Does this help you.
formatNumber
function formatNumber( num ) {
var decimalPart = '';
num = num.toString();
if ( num.indexOf( '.' ) != -1 ) {
decimalPart = '.'+ num.split( '.' )[1];
num = parseInt(num.split( '.' )[0]);
}
var array = num.toString().split( '' );
var index = -3;
while ( array.length + index > 0 ) {
array.splice( index, 0, ',' );
index -= 4;
}
return array.join( '' ) + decimalPart;
}
A simple add commas function is:
function addCommas(num) {
var num = String(num);
var bits, num0, s, f, len, sign = '', result = [];
if (/^[+-]/.test(num)) {
sign = num.substring(0,1);
num = num.substring(1);
}
bits = String(num).split('.');
num0 = bits[0];
s = 0, f = num0.length % 3 ;
len = num0.length;
if (num0.length > 3) {
while (f <= len) {
f && result.push(num0.substring(s, f));
s = f;
f += 3;
}
result = result.join(',') + (bits[1]? '.' + bits[1] : '');
}
return sign + (s? result : num);
}
There are probably a million similar functions, try Google.
Edit
Fixed issue where length > 6 and num % 3 == 0
Added support for -ve numbers
A little late but...
printf will add commas.
util.printf("%,0.0f", numberValue);
See JavaScript™ for Acrobat® API Reference for more...
This solution will also work for negative numbers as well.
function addCommas( num ) {
var parts = num.toString(10).split(".");
parts[0] = parts[0].reverse().replace(/(\d{3})/g, "$1,").reverse();
return parts.join(".");
}
String.prototype.reverse = function () {
return this.split("").reverse().join("");
}
Fiddle here