I want to perform addition of floating point numbers. I will always have always have only 2 decimal places.
However if I do:
var num = 0;
num += parseFloat("2434545.64").toFixed(2);
num += parseFloat("454560.91").toFixed(2);
I get the value as 02434545.64454560.91
It is appending instead of adding. Also will the addition be accurate always?
toFixed() return a String.
So you concatenate two String.
You should use toFixed() only in the last statement and you should not mix this invocation with a += operator in a even statement because here :
num += parseFloat("2434545.64").toFixed(2);
parseFloat("2434545.64").toFixed(2) is evaluated first.
It produces a String.
Then its num += String result is evaluated.
So, it would concatenate a Float with a String. Which produces again a String concatenation and not an arithmetic operation.
Just invoke toFixed() in a distinct statement :
var num = 0;
num += parseFloat("2434545.64");
num += parseFloat("454560.91");
num = num.toFixed(2);
Here you go with the solution
var num = 0;
num += 2434545.64;
num += 454560.91;
console.log(parseFloat(num).toFixed(2));
Here is the documentation for parseFloat https://www.w3schools.com/jsref/jsref_parsefloat.asp
Related
This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
Closed 5 years ago.
I encountered this strange supposed operator and am having trouble figuring out what it is. Any ideas?
var laugh = function(num){
var string="";
for (i=0; i<+num; i++) {
string+="ha";
}
return string + "!";
};
console.log(laugh(10));
One of the purposes of the + sign in JS is to parse the right part into the number.
const str = '4';
console.log(str + 5); // Concatenared as strings
console.log(+str + 5); // Sums the numbers
In your case you have an statement i < +num, which just parses num into number and i compares with it. If your num is a number, this will do nothing.
Look. I have used '10' instead of 10 and it still works, because the given string is parsed into number.
var laugh = function(num) {
var string="";
for (var i = 0; i < +num; i++) {
string+="ha";
}
return string + "!";
};
console.log(laugh('10'));
<+ is not an operator. You may interpret it simply as for (i=0; i < +num; i++) where + is the unary plus operator. The unary plus operator will coerce num into a number.
For example, if the value passed to num was "100" (as a String), the unary plus operator would coerce it to 100 (a Number).
MDN contains some examples of unary plus and other arithmetic operators.
This is the way this is parsed;
i < +num
In other words, num is being coerced to an integer before < is run on it.
There is no <+. They are parsed as separate symbols.
totalvalue = 0;
for (x=1; x<6; x++)
{
totalvalue += document.getElementById("rcv_amount_"+x).value;
}
rcv_amount_1 = 2
rcv_amount_2 = 4
rcv_amount_3 = 6
expected result is 12, but i am getting 0246.
Any help?
You have to convert the .value into a number - initially the .value property of an <input> element is a string, so the += operator results in concatenation, not addition.
To convert a string value into a number you can use parseInt(..., 10) for integers, or parseFloat(...) or just +(...) for non-integers.
Try with
totalvalue += parseInt(document.getElementById("rcv_amount_"+x).value, 10);
What's the best way to get the Nth digit of a number in javascript?
For example, for 31415926, the function will return 1 if N=2.
EDIT: And if possible, tu return directly a number, not a string.
EDIT 2: It is from left to right.
Try with that : (''+number)[nth] or (''+number)[nth-1] if one-based.
Personally, I would use:
function getNthDigit(number, n){
return parseInt((""+number).charAt(n));
}
But if you don't want it to be in String form ever you could use:
function getNthDigit(number, n){
var num = number,
digits = 0;
do{
num /= 10;
digits++;
}while(num>=1);
num = number / Math.pow(10, (digits - n));
num -= num % 1;
return (num % 10);
}
On second thought, just use the first option.
UPDATE: I didn't consider the fact that it was counting from the right. My bad!
Anyway, considering that the input is STILL a string, I'd use the same function, just with a little tweak.
Why don't you use the CharAt function? I think is the best option, considering the risk of multi-byte strings!!!
EDIT: I forgot the example:
var str = "1234567";
var n = str.charAt(str.length-2); // n is "6"
How can we convert a JavaScript string variable to decimal?
Is there a function such as:
parseInt(document.getElementById(amtid4).innerHTML)
Yes -- parseFloat.
parseFloat(document.getElementById(amtid4).innerHTML);
For formatting numbers, use toFixed:
var num = parseFloat(document.getElementById(amtid4).innerHTML).toFixed(2);
num is now a string with the number formatted with two decimal places.
You can also use the Number constructor/function (no need for a radix and usable for both integers and floats):
Number('09'); /=> 9
Number('09.0987'); /=> 9.0987
Alternatively like Andy E said in the comments you can use + for conversion
+'09'; /=> 9
+'09.0987'; /=> 9.0987
var formatter = new Intl.NumberFormat("ru", {
style: "currency",
currency: "GBP"
});
alert( formatter.format(1234.5) ); // 1 234,5 £
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
This works:
var num = parseFloat(document.getElementById(amtid4).innerHTML, 10).toFixed(2);
An easy short hand way would be to use +x
It keeps the sign intact as well as the decimal numbers.
The other alternative is to use parseFloat(x).
Difference between parseFloat(x) and +x is for a blank string +x returns 0 where as parseFloat(x) returns NaN.
It is fairly risky to rely on javascript functions to compare and play with numbers. In javascript (0.1+0.2 == 0.3) will return false due to rounding errors. Use the math.js library.
I made a little helper function to do this and catch all malformed data
const convertToPounds = (str = "", asNumber = false) => {
let num = Number.parseFloat(str);
if (isNaN(num) || num < 0) num = 0;
if (asNumber) return Math.round(num * 1e2) / 1e2
return num.toFixed(2);
};
Demo is here
Prefix + could be used to convert a string form of a number to a number (say "009" to 9)
const myNum = +"009"; // 9
But be careful if you want to SUM 2 or more number strings into one number.
const myNum = "001" + "009"; // "001009" (NOT 10)
const myNum = +"001" + +"009"; // 10
Alternatively you can do
const myNum = Number("001") + Number("009"); // 10
I have a function that I'm using to remove unwanted characters (defined as currency symbols) from strings then return the value as a number. When returning the value, I am making the following call:
return parseFloat(x);
The problem I have is that when x == "0.00" I expect to get 0.00 (a float with two decimals) back. What I get instead is simply 0.
I've also tried the following:
return parseFloat(x).toFixed(2);
and still get simply 0 back. Am I missing something? Any help would be greatly appreciated.
Thank you!!
parseFloat() turns a string into a floating point number. This is a binary value, not a decimal representation, so the concept of the number of zeros to the right of the decimal point doesn't even apply; it all depends on how it is formatted back into a string. Regarding toFixed, I'd suggest converting the floating point number to a Number:
new Number(parseFloat(x)).toFixed(2);
this should work:
return parseFloat(x).toFixed(2);
you can test it by running this in firebug:
var x = '0.00';
alert(parseFloat(x).toFixed(2));
simple:
function decimalPlaces(float, length) {
ret = "";
str = float.toString();
array = str.split(".");
if (array.length == 2) {
ret += array[0] + ".";
for (i = 0; i < length; i++) {
if (i >= array[1].length) ret += '0';
else ret += array[1][i];
}
} else if (array.length == 1) {
ret += array[0] + ".";
for (i = 0; i < length; i++) {
ret += '0'
}
}
return ret;
}
console.log(decimalPlaces(3.123, 6));
For future readers, I had this issue as I wanted to parse the onChange value of a textField into a float, so as the user typed I could update my model.
The problem was with the decimal place and values such as 12.120 would be parsed as 12.12 so the user could never enter a value like 12.1201.
The way I solved it was to check to see if the STRING value contained a decimal place and then split the string at that decimal and then count the number of characters after the place and then format the float with that specific number of places.
To illustrate:
const hasDecimal = event.target.value.includes(".");
const decimalValue = (hasDecimal ? event.target.value.split(".") : [event.target.value, ""])[1];
const parsed = parseFloat(event.target.value).toFixed(decimalValue.length);
const value = isNaN(parsed) ? "" : parsed;
onEditValue(value);
Here is dynamic version of floatParser for those who need
function customParseFloat(number){
if(isNaN(parseFloat(number)) === false){
let toFixedLength = 0;
let str = String(number);
// You may add/remove seperator according to your needs
[".", ","].forEach(seperator=>{
let arr = str.split(seperator);
if( arr.length === 2 ){
toFixedLength = arr[1].length;
}
})
return parseFloat(str).toFixed(toFixedLength);
}
return number; // Not a number, so you may throw exception or return number itself
}