Getting NaN when adding variables which consists of another variables - javascript

var dml = 30
var dd = parseFloat(document.getElementById("DriverD").value) <----- Only numbers like 10
var dm = dd-dml
alert((dd - dml) * 0.75) <----- This works
alert(dm * 0.75) <----- This returns NaN
alert(typeof(dm)) <----- This show that dm is a Number
I'm not sure why I keep getting NaN. I already tried parseFloat and parseInt but still showing NaN when multiplying a variable (dm) which consists of variables (dd-dml). dm is the result of subtracting dml with dd or 10-30. Please share your solutions.
I'm new here and I need help, please don't troll :) I am trying to add a cost calculator to my website.

It seems fine to me.
I want to tell another possible problem: You dont check if document.getElementById("DriverD").value is a number or not. If a user enters a string or other type, it will cause a problem.

Try this
Two operands must be convert to parseFloat
<input type="text:" value="10" id="DriverD" />
var dml = parseFloat(30);
var dd = parseFloat(document.getElementById("DriverD").value);
var dm = dd-dml;
alert(dm * .10);
Result is -.2

The only reason you could get NaN here is that the value of dd is NaN. Because the value of dm is defined as dd - dml and the value of dml is a Number value, 30.
parseFloat() always returns a Number value. The - operator converts its operands to Number only if necessary. So the value of dm must by definition be a Number value.
However, NaN is a Number value (typeof NaN === "number"), and it is "toxic": once an operand is NaN, the result of all following arithmetic operations is NaN.
That means that parseFloat() must have returned NaN, which means that the argument to parseFloat() could not be interpreted as the prefix of a decimal number representation.
One common reason for that is that the user has typed thousands separators (which are not supported) or a decimal comma while only a decimal point is supported.

Try this one
var dml = 30;
var dd = parseFloat(document.getElementById("DriverD").value) ; <----- Only numbers like 10
var dm=0;
dm = dd-dml;
alert((dd - dml) * 0.75); <----- This works
alert(dm * 0.75); <----- This returns NaN
alert(typeof(dm)); <----- This show that dm is a Number

I am a newbie but I think it is the type error, solution:
var someV = parseInt(document.getElementById("some-v-id").value, 10) || 0,
parseInt(value, 10) - you know because you used parse float, but two pipes and zero might prevent you from NaN as JavaSrcipt might be treating 0 as a string.

Related

How to add decimals to a number in JavaScript?

I am currently trying to add two decimal places to the end of the number 1000 (I need it to be 1000.00)
I am trying to use: parseFloat(1000).toFixed(2) but it keeps returning a string. When I do parseFloat((1000).toFixed(2)) it returns a number, but gets rid of the decimal places. Is there a way to convert the number 1000 into the number 1000.00 without returning a string?
Try to use .toLocaleString()
var n = 1000;
var nWithZerto = n.toLocaleString("en",{useGrouping: false,minimumFractionDigits: 2});
Since, Javascript treat both integer and, decimal as Number, so it doesn't matter in calculation.
But, if you are printing it then only you require formatting and it can be done as (1000).toFixed(2)-> string.

parsing string to decimal doesn't return decimals JavaScript

I'm new to writing JavaScript, I'm trying to convert two values from a string to a number, however, I have tried to doing the following approaches but none seem to work.
Example:
const num = parseInt('100.00') // returns 100
const num = Number('100.00') // returns 100
const num = +'100.00'; // returns 100
I need to return 100.00 as a number I have gone to other similar post they didn't seem to help, all knowledge is appreciated thanks!
In Javascript everything is Number, which is double-precision floating point 64 bit number (=decimal).
100.00 is equal to 100, therefore it shows you 100.
What you are asking is not possible, the decimal 100 is not representable as 100.00 as number, you can only represent it as a String with help of toFixed;
var num = 100;
var strNum = num.toFixed(2); // in this case you have a string instead of a number
console.log(typeof num, num);
console.log(typeof strNum, strNum);
It seems to me that all the approaches you have tried work.
Internally, JavaScript stores all numbers using the floating point format. It uses the minimum number of decimals needed when it displays the value.
This is 0 for integer numbers as 100. 100.00 is still 100, adding any number of 0 after the decimal point doesn't change its value.
The recommended method to parse a string that looks like a number is to use Number.parseInt() or Number.parseFloat().
parseFloat() recognizes only numbers written in base 10 but parseInt() attempts to detect the base by analyzing the first characters of the input string. It automatically recognizes numbers written in bases 2, 8, 10 and 16 using the rules described in the documentation page about numbers. This is why it's recommended to always pass the second argument to parseInt() to avoid any ambiguity.
Regarding your concern, use Number.toFixed() to force its representation using a certain number of decimal digits, even when the trailing digits are 0:
const num = parseInt('100.00');
console.log(num); // prints '100'
console.log(num.toFixed(2)); // prints '100.00'

Javascript String to int conversion

I have the following JS immbedded in a page:
var round = Math.round;
var id = $(this).attr("id");
var len = id.length;
var indexPos = len -1; // index of the number so that we can split this up and used it as a title
var pasType = id.substring(0, indexPos); // adult, child or infant
var ind = round(id.substring(indexPos)); // converts the string index to an integer
var number = (id.substring(indexPos) + 1); // creates the number that will go in the title
window.alert(number);
id will be something like adult0, and I need to take that string and split it into adult and 0 - this part works fine.
The problem comes in when I try to increment the 0. As you can see I use Math.round to convert it to an integer, and then add 1 to it - I expect 0 to be 1 after this. However, it doesn't seem to be converting it to integer, because I get 01, not 1. When testing this with adult1 the alert I get is 11.
I'm using this question for reference, and have also tried var number += id.substring(indexPos);, which breaks the JS (unexpected identifier '+=')
Does anyone know what I'm doing wrong? Is there a better way of doing this?
The parseInt() function parses a string and returns an integer,10 is the Radix or Base
[DOC]
var number = parseInt(id.substring(indexPos) , 10 ) + 1;
This is to do with JavaScript's + in operator - if a number and a string are "added" up, the number is converted into a string:
0 + 1; //1
'0' + 1; // '01'
To solve this, use the + unary operator, or use parseInt():
+'0' + 1; // 1
parseInt('0', 10) + 1; // 1
The unary + operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt() is self-explanatory (converts into number, ignoring decimal places).
The second argument is necessary for parseInt() to use the correct base when leading 0s are placed:
parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what
There's also parseFloat() if you need to convert decimals in strings to their numeric value - + can do that too but it behaves slightly differently: that's another story though.
Convert by Number Class:-
Eg:
var n = Number("103");
console.log(n+1)
Output: 104
Note:- Number is class. When we pass string, then constructor of Number class will convert it.
JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:
var numberAsInt = parseInt(number, 10);
// Second arg is radix, 10 is decimal.
If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.
Although parseInt is the official function to do this, you can achieve the same with this code:
number*1
The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.
Use parseInt():
var number = (parseInt(id.substring(indexPos)) + 1);` // creates the number that will go in the title
If you are sure id.substring(indexPos) is a number, you can do it like so:
var number = Number(id.substring(indexPos)) + 1;
Otherwise I suggest checking if the Number function evaluates correctly.

whole number in javascript?

I get 28.6813276578 when i multiply 2 numbers a and b, how can i make it whole number with less digits
and also, when i multiply again i get results after first reult like 28.681321405.4428.68 how to get only one result ?
<script>
$(document).ready(function(){
$("#total").hide();
$("#form1").submit(function(){
var a = parseFloat($("#user_price").val());
var b = parseFloat($("#selling").val());
var total = a*b;
$("#total").append(total)
.show('slow')
.css({"background":"yellow","font-size":50})
;
return false;
});
});
</script>
You can do several things:
total = total.toFixed([number of decimals]);
total = Math.round(total);
total = parseInt(total);
toFixed() will round your number to the number of decimals indicated.
Math.round() will round numbers to the nearest integer.
parseInt() will take a string and attempt to parse an integer from it without rounding. parseInt() is a little trickier though, in that it will parse the first characters in a string that are numbers until they are not, meaning parseInt('123g32ksj') will return 123, whereas parseInt('sdjgg123') will return NaN.
For the sake of completeness, parseInt() accepts a second parameter which can be used to express the base you're trying to extract with, meaning that, for instance,
parseInt('A', 16) === 10 if you were trying to parse a hexidecimal.
See Math.round(...).
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/round
In addition to the other answers about rounding, you are appending the answer to "total" by using
$("#total").append(total)
You need to replace the previous text rather than appending by using
$("#total").html(total)

I need to round the number of a field

I have tried many things about the rounding of a filed but I get NaN, here is what I am trying to round up to 999999,9
document.forms[0].NB_CONCN_MOY_DCO_MS
I have tried Math.round(document.forms[0].NB_CONCN_MOY_DCO_MS.value)
and
document.forms[0].Math.round(NB_CONCN_MOY_DCO_MS.value)
what can I do now.
If you want to round a number to one decimal place in JavaScript, use someNumber.toFixed(1). Note that the value of form fields is a string (not a number) so you'll want to convert it to a number first.
var n = document.forms[0].NB_CONCN_MOY_DCO_MS.value * 1;
var rounded = n.toFixed(1);
If your value has commas in it to represent decimal values, you will need to fix the string to use periods instead first:
var n = document.forms[0].NB_CONCN_MOY_DCO_MS.value.replace(/,/,',') * 1;
var rounded = n.toFixed(1);

Categories