Multiply a number which has a comma with javascript - javascript

Im trying to multiply a value which contains a comma(lets keep this comma). I cant find anything that seem to work, as everything that I have tried returns as NaN.
var value = 2,55;
// value = 44.000,55 also possible
var amount = 117;
var total = value * amount;
alert(total);//returns NaN

var value = 2,55;
That is not 2.55; it is 2, a comma and then 55. If I put that into the console of the dev tools of a chromium based browser I get "Uncaught SyntaxError: Unexpected number".
Because it is not valid syntax, in a var expression commas are used to define multiple locals.
JavaScript number literals can only use a period as a decimal separator: while parsing functions (converting from strings at runtime) can supper internationalisation the source code does not.
If you are creating code dynamically, the code to create the code has to handle creating syntactically correct code:
var value = 2.55; // or 4000.55

Assuming you are trying to operate on monetary values, it would be better to get the value as a string and convert it to float then back to string if you want to keep the comma:
var value = "2,55";
var amount = 50123123123;
var total = parseFloat(a.replace(',', '')) + b;
total = total.toString().split("").reverse().join("").split('').reduce((a, e, i)=> a + e + (i % 3 === 2 ? ',' : ''), '');
total=total.split("").reverse().join("");

Related

JavaScript - Using localStorage to save numbers: how to extract numbers from localStorage [duplicate]

I store a lot of values in localStorage for an app and needed a way of converting the "string" back into a number - IF it was a number. The thought being if you force HTML <input type="number"> on your form, then the data going into the form and extracted from the form IS a number, but once stored - its converted to a string. So to repopulate that field later, you must read the localStorage value and convert it back to a number before repopulating the input field - otherwise you start getting a lot of reptitive warnings and sometimes errors because NUMBERS are expected, but localStorage is retrieving strings.
My method: Assuming the value is inputted as a number, then only a number (digits only) will be stored - thus you can assume only numbers will come out (even if they are a string). Knowing only numbers will come back allows for this:
var allVariables = {} ;
var reg = new RegExp(/^\d+$/) ; // this accounts for digits only
for (var x=0; x<localStorage.length;x++) {
var keyValue = localStorage.getItem(localStorage.key(x)) ;
if (reg.text(keyValue)) {
keyValue = parseInt(keyValue) ;
}
allVariables[localStorage.key(x)] = keyValue ;
}
I even expanded on this to account for true/false booleans...can't use 0/1 easily without get confused with a number. Another method I have seen is underscoring the key name to identify the typeof for later conversion:
ie:
key1_str
key2_boo
key3_int
key4_obj
key5_flo
Then identify the "_xxx" to convert that value appropriately.
I am asking to see others approach to this problem or suggestions and recommendations on how to improve it. Mine is not perfect...though neither is localStorage...but still looking for improvement.s
suppose you have "keyName" : "12345".
Tricky solution is var newInt = +localStorage.getItem('keyName')
this extra + will convert the string to integer.
Instead of storing lots of single keys you might consider storing whole objects to less numbers of storage keys that you stringfiy to json and parse when retrieving. JSON methods will retain type
var obj= {
id:100,
anotherProp:'foo'
}
localStorage.setItem('myObj',JSON.stringify(obj));
var newObj = JSON.parse(localStorage.getItem('myObj'));
console.log(typeof newObj.id)//number
try to convert:
function getProbablyNumberFromLocalStorage(key) {
var val = localStorage.getItem(key);
return (isNan(+val) || val==null) ? val : +val;
}

How to parseInt or ParseInt embedded data with TypeScript in Qualtrics?

Even when I save an integer to embedded data earlier in the survey flow (in previous blocks on different screens), I am not able in Javascript to get the embedded data value, ensure it is parsed as a number/integer, then use it in a loop. Is this something about TypeScript? I didn't see anything about parseInt or ParseInt in the TypeScript documentation.
For example, suppose I do the following:
// Draw a random number
var x = Math.floor(Math.random() * 5);
// Save it in embedded data
Qualtrics.SurveyEngine.setEmbeddedData("foo", x);
// In a later block on a different screen, get the embedded data as an integer
var x_new = "${e://Field/foo}"; // not an int
var x_new = parseInt("${e://Field/foo}"); // doesn't work
var x_new = ParseInt("${e://Field/foo}"); // doesn't work
// Loop using x_new:
for(i = 0; i < x_new; i++) {
console.log(i)
}
Any idea why this isn't working? Perhaps I just don't know how to parseint().
In "normal" JS runtime system, we have parseInt function, the function gets a string (like number string) as a parameter. In this env, we don't support your syntax - "${e://Field/foo}", because it is not a "number string".
In Qualtrics system environment they have parseInt too, but they support their custom syntax "${e://Field/foo}" to get EmbeddedData.
Make sure that your code is running on Qualtrics system environment.
ParseInt is just turning your string into an integer.
Look at the demo below.
let myVar = "${e://Field/foo}"; // This is a string
console.log(myVar); // This prints a string
console.log(parseInt(myVar)); // This prints "NaN", i.e. Not a Number, because the string isn't a representation of a number.

wanted to add two floating number which gets concatenated as string

i want to add two float number with fixed two decimal but its converted to string and get concatenated.I know its simple question but actually i'm in hurry
var a=parseFloat("15.24869").toFixed(2)
var b=parseFloat("15.24869").toFixed(2)
Update when i enter input as
var a=parseFloat("7,191");
var b=parseFloat("359.55");
c=(a+b).toFixed(2)
O/P:NAN
why so?
The .toFixed() method returns a string. Call it after you've performed the addition, not before.
var a=parseFloat("15.24869");
var b=parseFloat("15.24869");
var c=(a+b).toFixed(2);
After that, c will be a string too, so you'll want to be careful.
As to your updated additional question, the output is not NaN; it's 366.55. The expression parseFloat("7,191") gives the value 7 because the , won't be recognized as part of the numeric value.
Just add parenthesys to parse float the whole result string
var a=parseFloat((15.24869).toFixed(2));
var b=parseFloat((15.24869).toFixed(2));
c=a+b
doing c = a + b adds the two answers together. You might just want to turn them into a string then concatenate them.
var a=parseFloat("15.24869").toFixed(2)
var b=parseFloat("15.24869").toFixed(2)
var c = (a.toString() + b.toString());

Converting Text Field to Numerical Value (Getting NaN)

I have this bit of code, it's supposed to take the value from one field, and calculate the value from it based on a certain percentage (in this case 60%).
I created a hidden field to store the value in the html, but when I run the calculation and check it in Firebug it gets a NaN value. Can anyone tell me what I can do to produce the number I need?
(Apply_RequestedAmtX_r != 0 & Apply_RequestedAdvanceAmtY_r !=0){
var AmtX= ($('#Apply_RequestedAdvanceAmtX_r').val());
var AmtY= ($("#Apply_AmtYAfterSplit_r").val());
var MaxAMT = parseInt((AmtY*60)/100);
$('#mna').val(MaxAMT
val returns a string. Now, the way you're using those variables, they'll get automagically converted to numbers (although it's best practice to parse them yourself).
One or the other of your values has a character in it that prevents the value from being automatically converted to a number; and then since that's NaN, any math involving it will be NaN. If you examine AmtX and AmyY in Firebug before using them, you should see whatever that character is.
Again, parsing isn't the actual problem here, but you're using parseInt in exactly the wrong place (unless you were trying to use it to truncate the fractional portion of the number, in which case there are better choices). Here are the right places:
var AmtX= parseInt($('#Apply_RequestedAdvanceAmtX_r').val(), 10);
var AmtY= parseInt($("#Apply_AmtYAfterSplit_r").val(), 10);
var MaxAMT = (AmtY*60)/100;
MaxAMT will likely have a fractional portion. If you want MaxAMT to be an integer, then:
var MaxAMT = Math.round((AmtY*60)/100);
// or
var MaxAMT = Math.floor(AmtY*60)/100);
// or
var MaxAMT = Math.ceil(AmtY*60)/100);
...depending on your needs.

Javascript format a number asin C#

I have a number which currently is 1,657,108,700 and growing. However I wish for it to show as
1,657,108k
Does javascript or html have a build in function to do this?
The value is being set throu javascript to a span field in html.
[edit]
From the comment I got my method as far as:
var start = '1,657,108,700';
start = (start / 1000).toFixed(0);
var finish = '';
while (start.length > 3)
{
finish = ','.concat(start.substring(start.length - 3, 3), finish);
start = start.substring(0, start.length - 3);
};
finish = start + finish + "k";
return finish;
however this returns 1,65,7k instead of 1,657,108k.. anyone know why?
var formattedNumber = Math.round(yourNumber / 1000).toLocaleString() + "k";
Turn the above into a function or not as appropriate. I'm not aware of a single function to do this, or of a way to cater for non-English versions of "k" (assuming there are some), but at least toLocaleString() should take care of the comma versus fullstop for thousands issue.
UPDATE: I posted the above without testing it; when I tried it out I found toLocaleString() formatted 1234 as 1,234.00. I had thought of fixing it by using a regex replace to remove trailing zeros except of course I can't be sure what character toLocaleString() is going to use for the decimal point, so that won't work. I guess you could write some code that uses toLocaleString() on a "control" number (e.g., 1.1) to see at runtime what character it uses for the decimal.
UPDATE 2 for your updated question, inserting the commas manually, I did it like this:
var unformattedNumber = 123456;
var a = unformattedNumber.toString().split("");
for (var i=a.length-3; i >0; i-=3)
a.splice(i,0,",");
var formattedNumber = a.join("") + "k";

Categories