I am trying to sum up the following numbers.
var number1= 12,000.00 ; var number2= 12,000.00;
I have tried this alert(number1+number2); but it doesn't return any data.
Could you please help me to solve this problem?
Thanks
The code in your question is invalid javascript. You can't have a , inside a numeric literal. You have to store it as a string, then parse it manually:
var number1 = '12,000.00';
var number2 = '12,000.00';
function parseCurrency( num ) {
return parseFloat( num.replace( /,/g, '') );
}
alert( parseCurrency(number1) + parseCurrency(number2) );
This won't work. Use accounting.js's unformat function to parse 12,000 as a string instead.
Related
I am trying to do a simple If function in zapier that returns a number between 1-10 based on another number input. for example if the number input is equal to 7200000 it should output 2. so far i have this:
if (inputData.num === '7200000') {
output = '2';
} else {
output = inputData.num;
}
This is giving me the error "You must return a single object or array of objects."
Can anyone help with this?
Thanks in advance :)
I found the solution,
Input Data: ms = TimeEstimate
var d = new Date(1000*Math.round(inputData.ms/1000));
function pad(i) { return ('0'+i).slice(-2); }
var str = d.getUTCHours() + ',' + pad(d.getUTCMinutes());
console.log(str);
output = [{str}];
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);">
I need to convert a formatted number to JS default number format.
This is my code:
String.prototype.toJsFloatFormat = function() {
debugger;
var newVal = this;
return newVal;
}
//Example of use
var input = 10000.22; //default js format
var formatted = input.toLocaleString("es"); // result is: 10.000,22
var unformatted = formatted.toJsFloatFormat(); //expected result = 10000.22;
The problem is when I need to get the formatted number (10.000,22) and I make operations with this formatted number (parseFloat(10.000,22) + 1000) I have bad results ( parseFloat(10.000,22) + 1000 = 1010)
thanks in advance.
It's not easy. There's a reason why most of the comments have said "Don't try -
do your calculations on the number itself, not the formatted value".
You need to work out what the decimal and thousand separator characters are. For that, you will need to know which locale the number was converted into.
(1234.5).toLocaleString("es").match(/(\D+)/g);
// -> [".", ","]
Once you have that, you can replace characters in the formatted string.
function unformatString(string, locale) {
var parts = (1234.5).toLocaleString(locale).match(/(\D+)/g);
var unformatted = string;
unformatted = unformatted.split(parts[0]).join("");
unformatted = unformatted.split(parts[1]).join(".");
return parseFloat(unformatted);
}
There is no way of working out the locale - you have to know it and pass it to the function.
no need to reinvent the wheel -
https://github.com/globalizejs/globalize#readme
var input = 10000.22;
Globalize.parseFloat(input );
I did it this way(in my case it was the 'ru' local format, so I did replace the 'space' symbol):
var myNumber = 1000000;
var formated = myNumber.toLocaleString('ru');
var unformated = parseInt(formated.replace(/\s/g, ''));
your case:
var formated = myNumber.toLocaleString('en');
var unformated = parseInt(formated.replace(/,/g, ''));
I did this, that's fine for me
function localeStringToFloat(locale){
if(!locale) return locale
let test=1000
test=test.toLocaleString(undefined,{minimumFractionDigits: 2,maximumFractionDigits: 2});
let separator=test[1]
let decimalSeparator=test[5]
return parseFloat(locale.replaceAll(separator,'').replace(decimalSeparator,'.'))
}
My functions for format and unFormat currency numbers to 'en-US'. I hope helps
function myFormatPrice(num,digits){
return num.toLocaleString('en-US', {maximumFractionDigits:digits});
}
function myUnFormatPrice(formated){
return parseFloat( formated.replaceAll(',','') );
}
Bear with me, I'm still kinda new to javascript.. I am trying to sort a list of save-game codes to be sorted by their first parse of the element.
var vList =["1|846|Doc|2|0|false|", "11|203|Derik|7|3|false|", "21|670|Mike|5|5|true|", "13|11|Ron|0|0|false|", "9|1000|Blood|9|9|true|"];
var vParse;
for (i = 0; i < (vParse.length); i++)
var vParse[i]= vList.split('|');
// then somehow sort all the data based on vParse[0]?
I tried a few sorting submissions from other folks, but I couldn't get it to ignore all the font after the first parse. Could anyone help me please?
You can use Array.sort and just split on the pipe, get the first item, and when subtracting the strings are converted to numbers anyway
var vList =["1|846|Doc|2|0|false|", "11|203|Derik|7|3|false|", "21|670|Mike|5|5|true|", "13|11|Ron|0|0|false|", "9|1000|Blood|9|9|true|"];
vList.sort(function(a,b) {
return a.split('|')[0] - b.split('|')[0];
});
console.log(vList)
Try some like that:
vList.sort( function( a, b ) {
return parseInt( a.split( '|' )[ 0 ] ) - parseInt( b.split( '|' )[ 0 ] );
} );
You can read more about sort, split and parseInt methods.
How about this
vList.map(function(el){return {sortBy : parseInt(el.split('|')[0]), original : el}}).sort(function(a,b){return a.sortBy - b.sortBy}).map(function(el){return el.original})
I am trying to get sum of rows of my table:
td1 val = $5,000.00; td2 val = $3000.00;
And I am using the following code:
var totalnum = 0;
$('.num').each(function(){
totalnum+= parseFloat($(this).html());
});
$('.total_num').html(totalnum);
This code works perfect if I remove money formatting from the number, otherwise it gives NaN as a result even if I am using parseFloat.
What am I missing?
Try:
var totalnum = 0;
$('.num').each(function(){
totalnum+= parseFloat($(this).html().substring(1).replace(',',''));
});
$('.total_num').html('$' + totalnum);
This will remove the $ (or whatever currency symbol) from the beginning and all commas before doing the parseFloat and put it back for the total.
Alternatively you could use the jQuery FormatCurrency plugin and do this:
totalnum+= $(this).asNumber();
If you add $ to the value, it is no longer an integer, and can no longer be calculated with.
Trying to make the formatted value back into a number is a bad idea. You would have to cater for different currency symbols, different formattings (e.g. 1.000,00) and so on.
The very best way would be to store the original numeric value in a separate attribute. If using HTML 5, you could use jQuery's data() for it:
<td class="num" data-value="1.25">$1.25</td>
....
var totalnum = 0;
$('.num').each(function(){
totalnum+= parseFloat($(this).data("value"));
});
$('.total_num').html(totalnum);
this way, you separate the formatted result from the numeric value, which saves a lot of trouble.
Try removing $ and any other character not part of the float type:
var totalnum = 0;
$('.num').each(function(){
var num = ($(this).html()).replace(/[^0-9\.]+/g, "");
totalnum+= parseFloat(num);
});
$('.total_num').html(totalnum);
Edit: updated replace to remove all non-numerical characters (except periods) as per this answer.