Values not being returned in JS - javascript

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);">

Related

I'm trying to use parseint but it does not work

I'm writing a script and I want a H1 tag to increase with an input's value. But it doesn't work. I'm probably dumb, but I'm here cause I want help.
This is my code:
var h1Value = 0;
function addFun() {
var changeH1By = document.getElementById('input').value;
parseInt('h1Value') + parseInt('changeH1By');
document.getElementById('h1').innerHTML = h1Value;
}
<h1 id="h1">0</h1>
<input type="number" id="input" value="1">
<button onclick="addFun()">Add</button>
As you probably see I'm using parseInt(), because else the h1 was "11". Like 1 + 1 = 11? Am I using the parseInt wrong or is something else wrong?
Thank you!
You were passing an string into parseInt, remove the quotes to pass the variable.
You didn't assign the result of parseInt('h1Value') + parseInt('changeH1By');to any variable
Instead off keeping track of var h1Value, lets use document.getElementById('h1').innerHTML to get the current value
Removed newValue so we can set the new value instant as innerHTML
function addFun() {
var currentvalue = document.getElementById('h1').innerHTML;
var changeH1By = document.getElementById('input').value;
document.getElementById('h1').innerHTML = parseInt(currentvalue) + parseInt(changeH1By);
}
<h1 id="h1">0</h1>
<input type="number" id="input" value="1">
<button onclick="addFun()">Add</button>
You're passing the strings "h1Value" and "changeH1By" to parseInt and it's trying to parse those literal strings to integers. If you try logging the result of e.g. parseInt("h1Value") it evaluates to NaN, i.e. "not a number", which would give you a hint of where you're going wrong.
A working version of your code would be
var h1Value = 0;
function addFun() {
var changeH1By = document.getElementById('input').value;
h1Value = h1Value + parseInt(changeH1By);
document.getElementById('h1').innerHTML = h1Value;
}
The type of h1Value is already a number, so it doesn't need to be coerced into one, and instead of calling parseInt with the literal string "changeH1By", you'll need to give the actual variable as an argument. Also the line
parseInt('h1Value') + parseInt('changeH1By');
doesn't do anything by itself, the javascript engine will just compute the value and throw it away, as you're not saving it into a variable etc.
A clean way for coding that...
<input..> elements of type="number" have a valueAsNumber property
use const to avoid repeating the results of these interpretations
const
h1_element = document.getElementById('h1')
, changeH1By = document.getElementById('input')
;
function addFun()
{
h1_element.textContent = changeH1By.valueAsNumber
+ parseInt(h1_element.textContent)
}
<h1 id="h1">0</h1>
<input type="number" id="input" value="1">
<button onclick="addFun()">Add</button>

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.

Javascript Math.log() help wanted

World!
I'm trying to create a program in Javascript that takes the log of a number typed into an HTML input. Unfortunately i've encountered a problem where it wont accept the string with the .replace().
Its Function:
I.E: When log(10) is calculated, the function should first remove the first 4 char's "log(" next remove the last parenthesis ")" and then take the log of the no. between.
HTML includes style elements, button and input form and an output < DIV >.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
//TESTING CODE
/*
if (inputString.value.startsWith("log(").endsWith(")"))
{
console.log(output.innerHTML = inputString.value.substring(4, 20).replace(")", ""));
}
else
{
output.innerHTML = "false";
}
*/
//Math.log() calc *****DOESNT WORK*****
if (inputString.value.startsWith("log(").endsWith(")"))
{
output.innerHTML = Math.log(inputString.value.replace(")", "").substring(4, 20));
}
else
{
output.innerHTML = inputString.value;
}
event.preventDefault();
}
If someone can give me an effective solution that would be much appreciated.
Thanks,
Syntax
Since Math.log() accepts only number values and you're trying to pass a string to it, you should first parse this value into a float number and then pass it to the log function:
let val = parseFloat(inputString.value.replace(")", "").substring(4, 20));
output.innerHTML = Math.log(val);
I'm guessing I got downvoted for being lazy, so here is the quick info. Gonras got it right relating to what you want to extract, but he forgot to check that what's being input is actually a log.
That's where the regex below comes in handy! I'm matching the field to:
^ start of word, since we want to match the entire field.
log(
([-.\d])) any consecutive sequence () of numbers (\d), -, and '.', represented by the []. The \(...\) makes sure to save this inner part for later.
$ is end of word, see 1.
res will be null if there is no match. Otherwise, res[0] is the entire match (so the entire input field) and res[1] is the first 'capture group', at point 3 - which is presumably the number.
This of course fails for multiple "-" inside, or "." etc... so think it over.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
var res = /^log\(([-.\d]*)\)$/.exec(inputString.value);
if (res)
output.innerHTML = Math.log(res[1]);
else
output.innerHTML = res;
}
document.getElementById("output").innerHTML='start';
calculate()
<div id='output'></div>
<input id='inpstr' value='log(2.71828)'></input>
If I wanted to fix your if to supplement Gonras's solution:
if (inputString.value.startsWith("log(") && inputString.value.endsWith(")"))
Yours fails since startsWith() returns a boolean, which obviously doesn't have a endsWith function.

How do I convert String to Number according to locale (opposite of .toLocaleString)?

If I do:
var number = 3500;
alert(number.toLocaleString("hi-IN"));
I will get ३,५०० in Hindi.
But how can I convert it back to 3500.
I want something like:
var str='३,५००';
alert(str.toLocaleNumber("en-US"));
So, that it can give 3500.
Is it possible by javascript or jquery?
I think you are looking for something like:
https://github.com/jquery/globalize
Above link will take you to git project page. This is a js library contributed by Microsoft.
You should give it one try and try to use formt method of that plugin. If you want to study this plugin, here is the link for the same:
http://weblogs.asp.net/scottgu/jquery-globalization-plugin-from-microsoft
I hope this is what you are looking for and will resolve your problem soon. If it doesn't work, let me know.
Recently I've been struggling with the same problem of converting stringified number formatted in any locale back to the number.
I've got inspired by the solution implemented in NG Prime InputNumber component. They use Intl.NumberFormat.prototype.format() (which I recommend) to format the value to locale string, and then create set of RegExp expressions based on simple samples so they can cut off particular expressions from formatted string.
This solution can be simplified with using Intl.Numberformat.prototype.formatToParts(). This method returns information about grouping/decimal/currency and all the other separators used to format your value in particular locale, so you can easily clear them out of previously formatted string. It seems to be the easiest solution, that will cover all cases, but you must know in what locale the value has been previously formatted.
Why Ng Prime didn't go this way? I think its because Intl.Numberformat.prototype.formatToParts() does not support IE11, or perhaps there is something else I didn't notice.
A complete code example using this solution can be found here.
Unfortunately you will have to tackle the localisation manually. Inspired by this answer , I created a function that will manually replace the Hindi numbers:
function parseHindi(str) {
return Number(str.replace(/[०१२३४५६७८९]/g, function (d) {
return d.charCodeAt(0) - 2406;
}).replace(/[०१२३४५६७८९]/g, function (d) {
return d.charCodeAt(0) - 2415;
}));
}
alert(parseHindi("३५००"));
Fiddle here: http://jsfiddle.net/yyxgxav4/
You can try this out
function ConvertDigits(input, source, target) {
var systems = {
arabic: 48, english: 48, tamil: 3046, kannada: 3302, telugu: 3174, hindi: 2406,
malayalam: 3430, oriya: 2918, gurmukhi: 2662, nagari: 2534, gujarati: 2790,
},
output = [], offset = 0, zero = 0, nine = 0, char = 0;
source = source.toLowerCase();
target = target.toLowerCase();
if (!(source in systems && target in systems) || input == null || typeof input == "undefined" || typeof input == "object") {
return input;
}
input = input.toString();
offset = systems[target] - systems[source];
zero = systems[source];
nine = systems[source] + 9;
for (var i = 0 ; i < input.length; i++) {
var char = input.charCodeAt(i);
if (char >= zero && char <= nine) {
output.push(String.fromCharCode(char + offset));
} else {
output.push(input[i]);
}
}
return output.join("");
}
var res = ConvertDigits('१२३४५६७८९', 'hindi', 'english');
I got it from here
If you need a jquery thing then please try this link
Use the Globalize library.
Install it
npm install globalize cldr-data --save
then
var cldr = require("cldr-data");
var Globalize = require("globalize");
Globalize.load(cldr("supplemental/likelySubtags"));
Globalize.load(cldr("supplemental/numberingSystems"));
Globalize.load(cldr("supplemental/currencyData"));
//replace 'hi' with appropriate language tag
Globalize.load(cldr("main/hi/numbers"));
Globalize.load(cldr("main/hi/currencies"));
//You may replace the above locale-specific loads with the following line,
// which will load every type of CLDR language data for every available locale
// and may consume several hundred megs of memory!
//Use with caution.
//Globalize.load(cldr.all());
//Set the locale
//We use the extention u-nu-native to indicate that Devanagari and
// not Latin numerals should be used.
// '-u' means extension
// '-nu' means number
// '-native' means use native script
//Without -u-nu-native this example will not work
//See
// https://en.wikipedia.org/wiki/IETF_language_tag#Extension_U_.28Unicode_Locale.29
// for more details on the U language code extension
var hindiGlobalizer = Globalize('hi-IN-u-nu-native');
var parseHindiNumber = hindiGlobalizer.numberParser();
var formatHindiNumber = hindiGlobalizer.numberFormatter();
var formatRupeeCurrency = hindiGlobalizer.currencyFormatter("INR");
console.log(parseHindiNumber('३,५००')); //3500
console.log(formatHindiNumber(3500)); //३,५००
console.log(formatRupeeCurrency(3500)); //₹३,५००.००
https://github.com/codebling/globalize-example
A common scenario for this problem is to display a float number to the user and then want it back as a numerical value.
In that case, javascript has the number in the first place and looses it when formatting it for display. A simple workaround for the parsing is to store the real float value along with the formatted value:
var number = 3500;
div.innerHTML = number.toLocaleString("hi-IN");
div.dataset.value = number;
Then get it back by parsing the data attribute:
var number = parseFloat(div.dataset.value);
This is a Columbus's egg style answer. It works provided the problem is an egg.
var number = 3500;
var toLocaleString = number.toLocaleString("hi-IN")
var formatted = toLocaleString.replace(',','')
var converted = parseInt(formatted)

javascript parse float error

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.

Categories