can't get the output from javascript - javascript

var weightkg=document.getElementById('weight').value;
var heightinm=document.getElementById('height').value;
function bmival (weightkg,heightinm){
var hout=heightinm*2
var output=weightkg/hout
//make a full number
// var r= Math.trunc(o)
if (output<=18.5){
return document.getElementById('print').innerHTML=`Your BMI is ${output} you are underweight` ;
}
else if(output>18.5 && o<25.5){
return document.getElementById('print').innerHTML=`Your BMI is ${output} You come under fit catogery`;
}
else{
return document.getElementById('print').innerHTML=`Your BMI is ${output} you are overweight and obese`;
}
}
[i am making a bmi cal that take input from user but i am getting a error and don't know what i am doing wrong]
**
this is js code and when i run i get a NaN instead of Number **

The values from an input field are strings so you must convert them into numbers
var heightinm = +document.getElementById('height').value; // one way to do it.

The value you get from
var weightkg=document.getElementById('weight').value;
seems to be a string instead of number. You need to convert values to do Math operations on them. NaN tells you output is not a number. Turn your values to number with parseInt method.
var weightkg = parseInt(document.getElementById('weight').value);
or you can just put a "+" to convert a string into number
var weightkg = +document.getElementById('weight').value;
For Example.
const input = document.getElementById('input');
const defaultStringInput = document.getElementById('input').value;
const inputConverted = parseInt(document.getElementById('input').value);
const inputConverted2 = +document.getElementById('input').value;
input.addEventListener('change', () => {
console.log(typeof defaultStringInput); // string
console.log(typeof inputConverted); // number
console.log(typeof inputConverted2); // number
});

Related

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 to revert toLocaleString

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(',','') );
}

Input field values not arithmetically summing up

Goodday, please i have a code to calculate the efficiency of a generator. The problem is the input fields all add up until the last variable. If all values were 2+2+3+4 which normally sums up into 11 normally, this program doesn't do that instead it just adds the 4 as in 2+2+3+4 equals 74.
That's the formula for calculating the efficiency of a generator.
$('.efmit').on('click', function efficiency() {
var vI = $('.I').val();
var vV = $('.V').val();
var ia = $('.ia').val();
var If = $('.If').val();
var Ra = $('.Ra').val();
var closs = $('.closs').val();
var vi_combo = vI*vV;
var ias = (ia*ia)*Ra;
var iv = If*vV;
var cent = 100;
var result = vi_combo+ias + iv;
var finalR = result + closs;
window.alert(finalR);
})
jQuery val method like $('.closs').val() returns String type variable not Number type.
You can cast type of variable to solve the problem.
var closs = Number($('.closs').val());
The reason is your program treated your variable as a string
try converting them to integer by parsing them like this parseInt(yourVariable).

Javascript handling fractions in variables

I'm new to programming and was trying to write a simple program to find the slope of a line, and I was wondering how I could handle variables with fractions in them. Currently, if I assign any of the variables as a fraction I will get an error.
var oneX = prompt ("what is the X of the first coordinate?");
var oneY = prompt ("what is the Y of the first coordinate?");
var twoX = prompt ("what is the X of the second coordinate?");
var twoY = prompt ("what is the Y of the second coordinate?");
console.log(oneX);
console.log(oneY);
console.log(twoX);
console.log(twoY);
var yRes = twoY-oneY;
var xRes = twoX-oneX;
console.log(yRes);
console.log(xRes);
var slope = yRes/xRes
console.log(slope);
If you have any advice for making this program neater too, I'd be happy for it. Thanks!
Dont use eval! Unless you know what eval is, why you should and shouldnt use it.
If you simply want to allow fractions then you should allow for parsing it. For instance you could simple write your code as such:
/*
* Tries to parse a users input, returns {#param input} as a number or
* attempts to parse the input as a fraction.
* #return Number or NaN if an invalid number or unparseable
*/
function parseUserInput(input) {
var res = +input;
if(isNaN(res)) {
// try parsing as fraction
var strval = String(input);
var ix = strval.indexOf('/');
if(ix !== -1) {
try {
res = strval.substring(0, ix) / strval.substring(ix+1);
} catch(e) {
}
}
}
return isFinite(res) ? res : NaN;
}
var oneX = parseUserInput(prompt ("what is the X of the first coordinate?"));
var oneY = parseUserInput(prompt ("what is the Y of the first coordinate?"));
var twoX = parseUserInput(prompt ("what is the X of the second coordinate?"));
var twoY = parseUserInput(prompt ("what is the Y of the second coordinate?"));
Or a very pretty way of writing it using #Jonasw's suggestion.
/*
* Tries to parse a users input, returns {#param input} as a number or
* attempts to parse the input as a fraction.
* #return Number or NaN if an invalid number or unparseable
*/
function parseUserInput(input) {
return +input.split("/").reduce((a,b)=> a/(+b||1));
}

Passing and returning an object to / from a function in Javascript.

I've done some digging on the above topic but am now more confused than when I started.
I have a unit converter that I'm working on.
It's working fine as a base model but I'm now trying to make it more modular.
There are many units and many conversions.
My plan is to have a function that determines what type of conversion is required, temperature, area etc etc, that can then call the appropriate function to carry out the math.
I'm very new to JS which isn't helping matters as it could be a simple mistake that I'm making but it's just as likely that I'm getting huge errors.
I think the problem is passing the object to the next function and then using it.
I've played with the code a great deal and tried many different suggestions online but still no success.
here is my code:
<script type="text/javascript">
function Convert(from, to, units, res){
this.from = from;
this.to = to;
this.units = units;
this.res = res;
}
Convert.convertUnits = function(){
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(this.units.val());
if(measurementType == "temp"){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Convert.prototype.convertTemp = function(){
var result = "invalid input";
var input = parseInt(this.units.val());
var f = this.from.val();
var t = this.to.val()
if(!isNaN(input)) {
if(f == "degC"){
if(t == "degF"){
result = input * 1.8 + 32;
}
if(t == "kelvin"){
result = input + 273.15;
}
}
}
console.log('Parsed input is', input, "and result is", result);
this.res.val(result);
return result;
}
//var calcTempTest = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
//var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
$("#btnConvert").click.convertUnits();
</script>
The first obvious problem is this line:
$("#btnConvert").click.convertUnits();
This tries to call a convertUnits() method defined on the click method of the jQuery object returned by $("#btnConvert"). There is no such method, so you get'll get an error about how click has no method 'convertUnits'.
What you want to be doing there is binding the convertUnits() function as a click handler, which you do by passing it to the .click() method as an argument:
$("#btnConvert").click(Convert.convertUnits)
It doesn't make sense to have declared convertUnits() as a property of Convert(), though, so (although it will work as is) I'd change it to just be:
function convertUnits() {
// your code here
}
$("#btnConvert").click(convertUnits);
The only other thing stopping the code working is that on this line:
var input = parseInt(this.units.val());
...you use this assuming it will be a Convert object with a units property but you haven't yet created a Convert object - you do that inside the if(measurementType == "temp") block with this line:
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
So move that line to the beginning of the function and then use test instead of this:
function convertUnits(){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(test.units.val());
if(measurementType == "temp"){
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Working demo: http://jsfiddle.net/jT2ke/
Some unrelated advice: parseInt() doesn't really make sense for a number to feed into your converter, because the user might want to enter decimal values. You can use parseFloat() instead, or the unary plus operator:
var input = +test.units.val();
But if you want parseInt() it is generally recommended to pass it a second argument to specify the radix:
var input = parseInt(test.units.val(), 10);
...because otherwise if the input text has a leading zero some browsers will assume the value is octal rather than base ten. (parseFloat() and the unary plus don't have that issue.)
I think you should not implement the method convertUnits inside Convert object. And the new code will look like the following:
convertUnits = function(){
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
if(measurementType == "temp"){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Now you can initiate the convertUnits on the button click:
$("#btnConvert").click(function(){new convertUnits()});

Categories