jQuery formating universal currency data [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to clear multiple currencies (like the US and EU) and round up. What I'm trying to do is;
10.30 → 10
10.60 → 11
849.95 → 850
1,022.20 → 1022
1.022,20 → 1022
230,20 → 230
30,20 → 30
I can do it if it's separated by a dot but the comma ones don't work https://jsfiddle.net/pmhgx7ut/

Building on what you already wrote, you can try the following:
var price = "1.022,20";
// comma and dot case
if (price.indexOf(',') < price.indexOf('.')) {
var price = price.replace(/[^0-9\.\,]/g, '');
var price = price.replace(",","");
};
// comma case
if (price.includes(",")==true && price.includes(".")==false)
{var price = price.replace(",",".");}
else //dot and comma case
{
if (price.indexOf('.') < price.indexOf(',')) {
var price = price.replace(",",".");
var price = price.replace(".",",");
var price = price.replace(/[^0-9\.\,]/g, '');
var price = price.replace(",","");};
};
var price = Math.round(price);
alert(price);

You should be able to do something like this:
prices = [
'£6,000.98',
'£6.000,98',
'£600.30',
'£600,30',
'£200',
];
prices.forEach(price => {
// Check for a dot or comma followed by 2 digits at the end of price
const cents_match = price.match(/[\,\.](\d{2})$/);
// Check if we got a match and round the calue, or set cents to 0
const cents = cents_match ? Math.round(cents_match[1] / 100) : 0;
// Get the price without cents, add the rounded cents value.
price = +(cents_match ? price.slice(0, price.length - 3) : price).replace(/\D/g, '') + cents;
// Output
console.log(price);
});

Related

how to add 1 in last item of array in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am solving one problem .but getting correct output for small array but my solution fail when array size is large
solution
/**
* #param {number[]} digits
* #return {number[]}
*/
var plusOne = function(digits) {
let str = parseInt(digits.join(''))+1+''
return str.split('')
};
Question
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
above cases are passed
failed cases
Input
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
Output
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,0,0,0]
Expected
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]
let str = parseInt(digits.join(''))+1+''
With too many array elements, you are simply creating a number that is outside of the integer range here.
An implicit conversion to a float has to happen, and with that you get the inherent loss of precision - which then leads to several zeros in those places at the end, when you reverse the process.
Access the last array element specifically, and add 1 to the value. But if that last element had the value 9 already, you will of course have to repeat that same process for the previous one … basic application of “carry the one”.
var input = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,9];
var output = [];
// loop over input array in reverse order
for(var i=input.length-1, toadd = 1; i>-1; --i) {
// add value `toadd` to current digit
var incremented = input[i] + toadd;
if(incremented < 10) {
output.unshift(incremented); // add to front of output array
toadd = 0; // reset toadd for all following digits, if we had no overflow
}
else {
output.unshift(0); // overflow occurred, so we add 0 to front of array instead
}
}
console.log(output)
This does take an “overflow” for 9 digits at the end into account; it does not handle the case when all digits are 9 though, if you need to handle that edge case as well, please implement that yourself.
This one recursively checks the last digits:
const test1 = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
const test2 = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,9]
const plusOne = function(digits) {
if(digits[digits.length - 1] === 9){
digits = [...plusOne(digits.slice(0, -1)), 0]
}else{
digits[digits.length - 1]++
}
return digits;
};
console.log(plusOne(test1));
console.log(plusOne(test2));
You could do something like this :
var arr = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3,9,9]
function plusOne(index){
if( index < 0 ) return ; // Base case
if(arr[index] === 9){
arr[index] = 0;
plusOne(index-1); // For carry ahead
}else{
arr[index] += 1
}
}
plusOne(arr.length-1) // start with last digit

I need to add a number from right to left in the decimal value using javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am trying to display decimal value in calculator using javascript.
if i click any buttons in the calculator, the button value added to decimal value from the right to left and it should be display in the screen.
For Eg: The default value is 0.00 if i click 2, it should be 0.02 and if i click 3, it should be 0.23 and if i click 4, it should be 2.34 and if i click 5, it should be 23.45 and so on.
You could try:
let number = 0;
// Returns the new value in case you need it to display in console
// and updates the number variable with the new value.
function addNumberRightToLeft(value) {
number = ((number * 10) + (value / 100)).toFixed(2);
return number;
}
console.log(addNumberRightToLeft(5)); // Shows '0.05' in console and updates number variable, so it is now '0.05'.
// or
addNumberRightToLeft(5); // Does not print to console but updates number variable, so it is now '0.55'.
or even use ES6 arrow functions and without side effects (as suggested by Nika):
const addNumberRightToLeft = (p, v) => ((p * 10) + (v / 100)).toFixed(2);
where p is the last value returned and v is what you want to add. In action:
let number = 0;
number = addNumberRightToLeft(number, 5); // 0.05
number = addNumberRightToLeft(number, 5); // 0.55
Like below: resultNum should be first initialize as 0.00;
function showCalc(inputNum)
{
var a = resultNum * 10.00;
var b = inputNum / 100;
resultNum = a + b;
return resultNum;
}

trying to add numbers in javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying to write a program to decrypt a encrypted message. The encrypted message is a very long set of numbers ".296.294.255.268.313.278.311.270.290.305.322.252.276.286.301.305.264.301.251.269.274.311.304.
230.280.264.327.301.301.265.287.285.306.265.282.319.235.262.278.249.239.284.237.249.289.250.
282.240.256.287.303.310.314.242.302.289.268.315.264.293.261.298.310.242.253.299.278.272.333.
272.295.306.276.317.286.250.272.272.274.282.308.262.285.326.321.285.270.270.241.283.305.319.
246.263.311.299.295.315.263.304.279.286.286.299.282.285.289.298.277.292.296.282.267.245.....ect".
Each character of the message is transformed into three different numbers (eg.first character of message is '230 .280 .264' second character is '.327.301.265' ect).
so i am trying to use javascript to add the groups of three numbers and then save them as their own variable. thanks
Assuming msg has that string in it, this will split it up and add the triplets together.
const [, triplets] = msg
.split('.')
.slice(1)
.map(v => +v)
.reduce(([count, list], val, i) => {
if ((i + 1) % 3) return [count + val, list];
return [val, list.concat(count)];
}, [0, []]);
It would depend on how the data is transmitted. It looks like you could bring the data in as a string (or parse it into a string) and then use the split method to create an array of all of your numbers.
var numbers = "234.345.456.567"
var arr = numbers.split(".")
You would then loop over the array doing whatever you need for every set of three
var newArray[]
var i
for(i = 0; i < length; i += 3){
//Add values here
//Parse back to int
newArray.push("sum Value")
}
Hope this was along the lines of what you need.
Use a regular expression to match all groups of three, then map each group to the number by splitting the string by .s and adding the 3 together:
const input = '296.294.255.268.313.278.311.270.290.305.322.252.276.286.301.305.264.301.251.269.274.311.304. 230.280.264.327.301.301.265.287.285.306.265.282.319.235.262.278.249.239.284.237.249.289.250. 282.240.256.287.303.310.314.242.302.289.268.315.264.293.261.298.310.242.253.299.278.272.333. 272.295.306.276.317.286.250.272.272.274.282.308.262.285.326.321.285.270.270.241.283.305.319. 246.263.311.299.295.315.263.304.279.286.286.299.282.285.289.298.277.292.296.282.267.245';
const groupsOfThree = input.match(/\d{3}\.\d{3}\.\d{3}\./g);
const sums = groupsOfThree.map((group) => {
const nums = group.split('.').map(Number);
return nums[0] + nums[1] + nums[2];
});
console.log(sums);

Algorithm to convert any string to a 1-3 digit number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to make an algorithm, for a NodeJS app, that converta any given string to a 1 to 3 digit number (better if the number is between 1-500).
e.g
ExampleString -> 214
Can anyone help me find a good solution?
EDIT:
I want to get a crime coefficient number from a username (string).
Ok, you can use JS function to get charCode of letter
let str = "some string example";
let sum = 0;
for (let i=0; i<str.length; i++) {
sum += parseInt(str[i].charCodeAt(0), 10); // Sum all codes
}
// Now we have some value as Number in sum, lets convert it to 0..1 value to scale to needed value
let rangedSum = parseFloat('0.' + String(sum)); // Looks dirty but works
let resultValue = Math.round(rangedSum * 500) + 1; // Same alogorythm as using Math.random(Math.round() * (max-min)) + min;
I hope it helps.
So as you are using nodejs, you can use crypto library to get md5 hash of string and then get it as HEX.
const crypto = require('crypto');
let valueHex = crypto.createHash('md5').update('YOUR STRING HERE').digest('hex');
// then get it as decimal based value
let valueDec = parseInt(valueHex, 16);
// and apply the same algorythm as above to scale it between 1-500
function coeficient() {
return Math.floor(Math.random() * 500) + 1;
}
console.log(coeficient());
console.log(coeficient());
console.log(coeficient());

jQuery quiz application how to implement a point based answering system? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
So I am reasonably new to javascript and jquery. I have been looking at tutorials which have been a good starting point however they all seem to have one question that is right, so they are able to check within a function if the users answer is correct via a if equal to statement for example.
if (answers[i] == userAnswers[i]) {
flag = true;
}
What I would like to do however, is have a different value attached to each of the potential answers for example
var 1 = 50
var 2 = 0
var 3 = 10
Question 1
var a = 1
var b = 2
var c = 3
var d = 3
Question 2
var a = 3
var b = 1
var c = 2
var d = 3
What would be the best way to do something like this?
First, an assumption:
answers[i] contains a number which is what the user picked as an answer to question i (Note: if answers[i] is in fact a character, you can get the integer value by subtracting answers[i] by the ascii value of 'a').
To do what you want to do, simply define a 2-dimensional array score[i][j], where i is the index of the question, and j is the option number (ie the asnwer to question i), then score[i][j] gives the score for this question. So let's say for question 1, the options are as you described above (ie a = good, b = wrong, ...), then you would have
//set the values for the answers
score[1][1] = good; score[1][2] = wrong; score[1][3] = wrong; score[1][4] = okay
score[2][1] = okay; score[2][2] = good; score[2][3] = wrong;
//more score setting
//get the value of the answer
var score_q1 = score[1][answers[1]]
var score_q2 = score[2][answers[2]]
ie, since answers[i] contains the value of the answer as a number, by calling score[question_nb][answers[question_nb]] you get the score for that question. In this case, there are no if statements. If you want to get the total score, just loop over all questions and sum up the score for that question.
The best way would be a key/value pair. I would try something like json. You would have your json with a key of good and a value (for points) as 50. The json would look something like below:
var kvPair = {"good":"50", "wrong":"0", "okay":"10"};
then when someone clicks an answer it would run ajax to determine the score:
$.ajax({
type: "POST",
dataType: "json",
url: "someUrl",
data: kvPair,
success: function (data) {
//do something with score data
},
error: function (event) {
ShowErrorLabel("ERROR in ajax call('someUrl'): \n" + "Error : " + event.status + " - " + event.statusText);
}
});

Categories