This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Strange javascript addition problem
I know there's obviously a solution for this, and I've done it before, but I can't remember it and now I can't find it.
<div>1</div>
$(function() {
var number = $('div').text();
var math = number + 2;
$('body').text(math);
});
http://jsfiddle.net/G5zdx/
number is not being treated as an integer so math's value is "12" instead of "3". How can I correct this?
There are many ways, but
var math = (1 * number) + 2;
is a simple one. Whether you should be detecting possible ill-formed non-numbers depends on the nature of the rest of your code.
The parseInt() function is useful, but it probably should be called with 10 as its second argument to avoid interpreting numbers that begin with zero as octal constants instead of decimal. Also, parseInt() will not treat a string like "23skidoo" as an error, which may or may not be OK in your application.
<div>1</div>
$(function(){
var number = parseInt($('div').text(), 10);
var math = number+2;
$('body').text(math);
});
You can parse a string as an int using parseInt(string[, radix]).
Your code would look as follows
$(function(){
var number = $('div').text();
var math = parseInt(number, 10)+2;
$('body').text(math);
});
Source: http://www.javascripter.net/faq/convert2.htm
Related
This question already has answers here:
convert '1' to '0001' in JavaScript [duplicate]
(4 answers)
Pad a number with leading zeros in JavaScript [duplicate]
(9 answers)
Closed 3 years ago.
Yep, the title says pretty much everything. Basically I want a default X-digit number which is all zeros. Then, from this number, I want to replace the last characters with other numbers. For example, if I have '434', and the default is '000000', the result should be '000434'.
In Ruby, this is the equivalent of doing '%.6d' % 434 and it returns '000434'. If the number I want to save has more than 6 digits, I just use that number instead. I realized that as I'm working with strings I could use this solution:
let base = '000000'
let str = '434'
console.log(base.slice(0, -str.length) + str)
Buuut, even if it's a simple approach, I don't know if it's the best. What daya' think?
For compatibility with older JS environments, you can depend only on a simpler slice:
(base + str).slice(-6)
For modern ones, padStart is available:
str.padStart(6, '0') // or String(num)
JavaScript has string.padStart(length, padString)
let str = '434'
const updated = str.padStart(6, '0')
console.log(updated)
This question already has answers here:
What's the best way to convert a number to a string in JavaScript?
(25 answers)
Closed 5 years ago.
What is the best way to convert a number to string in javascript?
I am familiar with these four possibilities:
Example 1:
let number = 2;
let string1 = String(number);
Example 2
let number = 2;
let string2 = number.toString();
Example 3
let number = 2;
let string3 = "" + number;
Example 4
let number = 2;
let string4 = number + "";
All examples giving the same result, but what is the best option to choose based on Performance? Or is it personal preference?
Thanks for answering.
The problem with approach #2 is that it doesn’t work if the value is null or undefined.
1st , 3rd and 4th which are basically equivalent.
""+value: The plus operator is fine for converting a value when it is surrounded by non-empty strings. As a way for converting a value to string, I find it less descriptive of one’s intentions. But that is a matter of taste, some people prefer this approach to String(value).
String(value): This approach is nicely explicit: Apply the function String() to value. The only problem is that this function call will confuse some people, especially those coming from Java, because String is also a constructor.
I am trying to get an 8 decimal output from the following function.
The following function multiplies an input by 2 and then updates this input with the wagerUpdate variable. I would like this outputted number to have 8 decimal places.
For example: if input number is 0.00000001 (this code is for a bitcoin website), then I would like output number to be 0.00000002. For some reason the code below is not working properly as the output number is in the format of 2e-8 without the .toFixed(8) code. Please help if you are able to. Thank you so much.
<script>
function MultiplyWagerFunction() {
var wager = document.getElementById("wagerInputBox").value;
var wagerUpdate = wager*2;
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
}
</script>
If you remove the + before wagerUpdate.toFixed(8) it should work fine. wagerUpdate has already be converted to a number when you multiplied it by 2 so there should be no need for the unary +
var a = "0.00000001";
var b = a*2;
console.log(b.toFixed(8));
console.log(+b.toFixed(8));
^ see the difference.
The reason it doesn't work is because what you are doing is equivalent to:
+(b.toFixed(8))
because of the precedence of the operators (member access . is higher than unary +). You are converting b to a string with .toFixed and then converting it back into a number with + and then converting it back into a string again! (this time with the default toString behavior for numbers giving you exponential notation)
Just remove + from +wagerUpdate.toFixed(8); and you would be good.
Instead of:
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
try:
document.getElementById("wagerInputBox").innerHTML = +wagerUpdate.toFixed(8);
Why I say so is may be when you set value, browser tries to convert to best possible outcome. But, inner HTML should take the string equivalent!
This question already has answers here:
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 7 years ago.
Im trying to round a number to 2 decimal place. I have tried the following but not having any luck? Can somebody please help me and tell me where im going wrong??
var winPercentage = totalWins/(totalWins+totalLost)*100;
winPercentage.toFixed(2);
document.getElementById('win-percentage').innerHTML = winPercentage + " %";
i search and tried this but to be honest i have no idea what it is?
var winPercentage = totalWins/(totalWins+totalLost)*100;
expr {double(round(100*winPercentage))/100}
document.getElementById('win-percentage').innerHTML = winPercentage + " %";
Try to use the following syntax instead and alter it to your needs
var num = 5.1;
num.toFixed(2); //will become 5.10
You had the right idea with toFixed(2). The problem is that it returns the formatted number, it does not alter the variable it was called on. In other words, you just need to assign it back the the variable you were using:
winPercentage = winPercentage.toFixed(2);
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 9 years ago.
I can't seem to get a nice number rounded to the nearest hundredth (ie. 12.57 instead of 12.57000000008).
var example = {
user : "John",
dollars: 12.57
};
setInterval( function() {
example.dollars += (parseInt(Math.floor(Math.random()*2000 + 500)) / 100);
console.log(example.dollars);
}, 1000);
I keep getting values like:
15.20000000008
88.54000000007
86.36000000008
Am I setting something wrong in my Math function?
Note: This is in node.js
Javascript numbers are floating point numbers. They should not be relied upon for precision decimal operations.
For instance you can enter this into a js console
.1 + .2 //0.30000000000000004
Generally you can count on integer mathematics accurately,and if you need more control on decimal accuracy, you can look into libraries like this one which lets you set error bounds on your numbers, or make a call to an external library written in a language with better handling of number types.
More libraries for accurate JS decimal math:
https://npmjs.org/package/decimal
https://github.com/iriscouch/bigdecimal.js
Try isolating the number to the hundredth place. ie [86.36]000000008
var example = {
user : "John",
dollars: 12.57
};
setInterval(function() {
var s, final;
example.dollars += (parseInt(Math.floor(Math.random() * 2000 + 500)) / 100);
s = example.dollars + .005 + '',
final = s.substring(0, s.indexOf('.') + 3);
console.log(final);
}, 1000);
All we are doing is removing everything after the hundredth decimal place. in order to do that we need to find the decimal place so we can find the hundredth decimal value per say. First we must convert the number into a string, + '' or you can use the toString() function. then we use indexOf('.') to find the decimal placement and finally we count three places over. that will get you the number to the hundredth place, without the long decimal values.
Examples:
input: 12.57000000008 output: 12.57
input: 15.20000000008 output: 15.20
Working fiddle.
If you only need to support modern browsers, the toFixed method is the best choice. It takes an argument representing the number of decimal places to round to and returns a String.
example.dollars.toFixed(2); // returns "12.57"