How to add float together as actual numerical values in Javascript - javascript

I am working on an app and part of it requires adding values together.
I have a form where a user can enter a dollar amount which allows floats i.e. 55.25 etc... When a a new item is submitted via the form, the totals get added together. Using whole numbers is easy but I want float numbers to be added together on each form submission. The struggle is that to get numbers to display I use parseFloat().toFixed(2) but adding strings together just gives a string value not a mathematical/decimal value.
How can I achieve this?
totalAmount(() => {
let totalPayment = '0.00';
if (items.length > 0) {
for (let i = 0; i < items.length; i++) {
let item = JSON.parse(JSON.stringify(items[i]));
totalPayment = parseFloat(totalPayment) + parseFloat(item.amount).toFixed(2);
}
}
return totalPayment;
}),
Input field
<input type="number" required min="0" id="amount" step=0.01>

You can put a + sign before each item to transform it to numerical and then .toFixed the result
totalPayment = (+totalPayment + +item.amount).toFixed(2)

Add first, then format with toFixed:
totalPayment = parseFloat(totalPayment) + parseFloat(item.amount);
totalPayment = totalPayment.toFixed(2);
Or:
totalPayment = parseFloat(totalPayment) + parseFloat(item.amount);
return totalPayment.toFixed(2);

Related

Values not being returned in JS

I have a value separated by commas. The code is as follows:
function addComma(values) {
const v = values.value && new Number(values.value.replace(/,/g, ''));
values.value = v.toLocaleString();
}
if (document.getElementById("values"))
var pay = document.getElementById("values").value;
payment = pay.replace(/\,/g, '');
<label>Rent</label> <input style="font-size:10px;width:80px;text-align:right" id="values" type="text" onkeyup="addComma(this);">
Issue:
if (selectedPayType === "A") {
PV = getNPV(rate, array, payment) + payment;
console.log("PV);
}
For some reason, PV returns the value but it doesn't add the +payment. But, instead of +payment, if i use the numeric value itself ex: 10000, then it adds the value up.
I tried debugging and it is taking the payment value inside the getNPV however, not adding it up which is really weird. Not sure what i am doing wrong here. Any help is appreciated. Thank you.
The main problem is that you are adding a string to a number . For eg: 1 + '2' = '12'. So you need to convert your payment which is a string, into a number.
Do not use Number constructor as it might cause unwanted results, but use parseFloat or parseInt to convert numeral strings into numbers.
p.s. for parseInt you should/need to specify a radix .
Useful links
parseInt()
parseFloat()
why avoid creating object versions of primitives
Changed a bit the structure ( added the if inside the addComma function that is called onkeyup )
See below
function addComma(values) {
const v = values.value && parseFloat(values.value.replace(/,/g, ''));
values.value = v.toLocaleString();
if (document.getElementById("values")) {
var pay = document.getElementById("values").value;
payment = pay.replace(/\,/g, '');
PV = 10 + parseFloat(payment);
console.log(PV);
}
}
<label>Rent</label> <input style="font-size:10px;width:80px;text-align:right" id="values" type="text" onkeyup="addComma(this);">

Formatting input type="text" in JS

I have a text field with type='text' and I am trying to format the text with commas. Example: 500000000 would become 500,000,000.
I have the following code:
function addComma(values) {
values.value = values.value.replace(",", "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
if (document.getElementById("values"))
payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
However, it's printing 5,000,0,0,0,000 and the formatting is off for some reason. I also tried .toLocaleString(), but that doesn't seem to work either. What am I doing wrong here?
I was referred to a few other posts on Stack Overflow, but nothing seems to work out.
function addComma(values) {
const v = values.value && new Number(values.value.replace(/,/g,''));
values.value = v.toLocaleString();
}
if (document.getElementById("values"))
payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
You can do this by converting the number to a string, then manually iterating over each character and find places where a comma is needed.
function formatNumber(number) {
var str = number.toString();
var offset = str.length % 3;
var newStr = '';
for (var i = 0; i < str.length; i++) {
if (i > 0 && i % 3 === offset) {
newStr += ',';
}
newStr += str[i];
}
console.log(str, '=>', newStr);
}
formatNumber(5);
formatNumber(50);
formatNumber(500);
formatNumber(5000);
formatNumber(50000);
formatNumber(500000);
formatNumber(5000000);
I'd recommend using a change event rather than a keyup event as change will only update the value when the input is no longer the focus. If you use keyup the code will try and reinterpret the new string you add back to the input as a number and throw an error.
Here's the code using toLocaleString (just press tab after adding the number as if to move to the next input box):
const values = document.querySelector('#values');
values.addEventListener('change', handleChange, false);
function handleChange(e) {
const value = Number(e.target.value);
const formatted = value.toLocaleString();
values.value = formatted;
}
<input id="values" type="text">
The other answers posted before this one using the input field are ok to show how it works, but they are bugged as soon as you enter a new number when it has formatted to a string using toLocaleString(). For that reason I added the toNumber() function to be complete. In the example below I preform the following steps:
When user fills in a number in the input field and leaves the input field: Call toString(e) and make from the entered number a formatted string.
If the user again selects the input field, call toNumber(e) and format it back to a number.
This makes sure you won't get NaN when reselecting or will become completely unusable.
The NaN property represents "Not-a-Number" value. This property indicates that a value is not a legal number.
It is still possible to add text in it, this will result in NaN as text cannot be formatted to a number. This could be filtered out in the toString(e) when necessary. I did this in the example below by adding if (formatted !== 'NaN') {} Only when it's not NaN it will set the value to the new formatted number. Else it won't do anything. Please note: a number with dots is a string in this case so wont work either.
const values = document.querySelector('#values');
values.addEventListener('click', toNumber, false);
values.addEventListener('focusout', toString, false);
function toNumber(e) {
const value = e.target.value;
const unformatted = value.replace(/\D/g,'');
values.value = unformatted;
}
function toString(e) {
const value = Number(e.target.value);
const formatted = value.toLocaleString();
if (formatted !== 'NaN') {
values.value = formatted;
}
}
<input id="values" type="text">
To fix that, you can also remove my addition and add a filter before the toString(e) does it's thing and filter the dots, text etc. so only the numbers remain.

How do I find the sum of numbers from multiple form input values in JavaScript?

I have 5 inputs that have prices in them. There is a sixth input that will display the total price by adding the prices of the first five inputs together.
function calculateTotal(){
var priceInputs = document.querySelectorAll("input[name^='tPriceInput']");
var totalPrice = 0;
for(var i = 0; i < priceInputs.length; i++){
totalPrice = totalPrice + parseInt(priceInputs[i].value);
}
return totalPrice;
}
The function above always returns NaN... Why does this not work? I have also tried without the parseInt method but that only adds the strings together.
There is not enough info but I assume from all you have said you use commas , in the price as a delimeter instead of dots ., but JavaScript requires dots. This is a common problem for non-english regional settings.
If so, try this:
totalPrice = totalPrice + parseInt(priceInputs[i].value.replace(",", "."));
change
var priceInputs = document.querySelectorAll("input[name^='tPriceInput']");
to
var priceInputs = document.querySelectorAll("input[name='tPriceInput']");

javascript arrays reading in form data best practice

I'm still quite new to javascript and was wondering if there's a more efficient way to handle this situation, for example by using an array?
I have an HTML form with 6 fields that let you enter the last six weeks amount of overtime paid. I'm then using javascript to add the six values up, divide by six and multiply by 52 to obtain an annual overtime amount. My fields are named w_ot_1, w_ot_2 up to w_ot_6 and I'm using the code below. It all works fine but I'm finding it's really repetitive and it's not just overtime I need to run this calculation on. I'm sure there's got to be a more efficient way. Does anyone have any ideas that could help?
var weekly_ot_1 = parseFloat(document.getElementById("w_ot_1").value.replace(/[^0-9.]/g, ''));
var weekly_ot_2 = parseFloat(document.getElementById("w_ot_2").value.replace(/[^0-9.]/g, ''));
var weekly_ot_3 = parseFloat(document.getElementById("w_ot_3").value.replace(/[^0-9.]/g, ''));
var weekly_ot_4 = parseFloat(document.getElementById("w_ot_4").value.replace(/[^0-9.]/g, ''));
var weekly_ot_5 = parseFloat(document.getElementById("w_ot_5").value.replace(/[^0-9.]/g, ''));
var weekly_ot_6 = parseFloat(document.getElementById("w_ot_6").value.replace(/[^0-9.]/g, ''));
//weekly annualised overtime values
document.getElementById("w_annual_ot").value= addCommas((((weekly_ot_1 + weekly_ot_2 + weekly_ot_3 + weekly_ot_4 + weekly_ot_5 + weekly_ot_6)/6) * 52).toFixed(2));
This is a situation where you can leverage a simple for loop and string concatenation when calling document.getElementById(). I would suggest creating a function to calculate the overtime paid and have the function take the number of weeks as a parameter so that you can easily change it if you add more fields.
function getOvertimePaid(numberOfWeeks) {
var total = 0;
// Iterate from 1 to the number of weeks and increment the total by
// the parsed value in the field for the current index
for (var i=1; i<=numberOfWeeks; i++) {
total += parseFloat(document.getElementById('w_ot_' + i).value.replace(/[^0-9.]/g, '');
}
// Return the annualized amount as a float for flexibility
return (total / numberOfWeeks) * 52;
}
// Update weekly annualised overtime values and provide formatting at this point
document.getElementById("w_annual_ot").value= addCommas(getOvertimePaid(6).toFixed(2));
Another thing you may want to look at to make the code and the supporting HTML even more flexible is to leverage a class name on your weekly overtime input elements. If you do that and adjust the code slightly you can add or remove fields at will and the function to calculate the annualized overtime will continue to work. As an example:
HTML
<input type="text" id="w_ot_1" class="weekly-overtime" value="0.00" />
<input type="text" id="w_ot_2" class="weekly-overtime" value="0.00" />
<input type="text" id="w_ot_3" class="weekly-overtime" value="0.00" />
JavaScript
function getAnnualizedValue(className) {
// Get all elements with the given class name
var elements = document.getElementsByClassName(className);
// Iterate the elements and keep a running total of their values
var total = 0;
for (var i = 0; i < elements.length; i++) {
total += parseFloat((elements[i].value || '0').replace(/[^0-9.]/g, '');
}
// Return the annualized amount as a float for flexibility
return (total / numberOfWeeks) * 52;
}
// Update weekly annualised overtime values and provide formatting at this point
document.getElementById("w_annual_ot").value= addCommas(getAnnualizedValue('weekly-overtime').toFixed(2));

show only last 4 digits in bank account using javascript

I need help with Javascript. I need to replace however many characters there are previous to the last 4 digits of a text field that contains bank account number. I have searched through the net on this, but cannot find one code that works. I did find a code here on stackoverflow, which was regarding credit card,
new String('x', creditCard.Length - 4) + creditCard.Substring(creditCard.Length - 4);
I just replaced the creditCard with accounNumObject:
var accounNumObject = document.getElementById("bankAcctNum")
The input is pretty simple.
<cfinput type="text" name="bankAcctNum" id="bankAcctNum" maxlength="25" size="25" value="#value#" onblur="hideAccountNum();">
Can anyone help please?
To replace a string with x except for the last four characters in JavaScript, you could use (assuming str holds the string)...
var trailingCharsIntactCount = 4;
str = new Array(str.length - trailingCharsIntactCount + 1).join('x')
+ str.slice(-trailingCharsIntactCount);
jsFiddle.
You could also use a regular expression...
str = str.replace(/.(?=.{4})/g, 'x');
If you want to add the 4 from a variable, construct the regex with the RegExp constructor.
jsFiddle.
If you're fortunate enough to have the support, also...
const trailingCharsIntactCount = 4;
str = 'x'.repeat(str.length - trailingCharsIntactCount)
+ str.slice(-trailingCharsIntactCount);
Polyfill for String.prototype.repeat() is available.
Here is a fiddle showing what you're asking for:
http://jsfiddle.net/eGFqM/1/
<input id='account' value='abcdefghijklmnop'/>
<br/>
<input id='account_changed'/>
var account = document.getElementById('account');
var changed = document.getElementById('account_changed');
changed.value = new Array(account.value.length-3).join('x') +
account.value.substr(account.value.length-4, 4);
Edit: Updated fiddle to correct off by one problem pointed out by alex
Agreed with all above solutions.I just had one another approach.
const maskAccountId = (accountId) => {
if (accountId) { /** Condition will only executes if accountId is *not* undefined, null, empty, false or 0*/
const accountIdlength = accountId.length;
const maskedLength = accountIdlength - 4; /** Modify the length as per your wish */
let newString = accountId;
for (let i = 0; i < accountIdlength; i++) {
if (i < maskedLength) {
newString = newString.replace(accountId[i], '*');
}
}
return newString;
} else return /**Will handle if no string is passed */
}
console.log(maskAccountId('egrgrgry565yffvfdfdfdfdfgrtrt4t4'));

Categories