This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I have two strings which contain only numbers:
var num1 = '20',
num2 = '30.5';
I would have expected that I could add them together, but they are being concatenated instead:
num1 + num2; // = '2030.5'
How can I force these strings to be treated as numbers?
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
MDN docs for parseInt
MDN docs for parseFloat
In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!
parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)
Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.
http://jsfiddle.net/EtX6G/
var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];
Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);
function Append(text) {
body.appendChild(document.createTextNode(text));
body.appendChild(document.createElement('br'));
}
I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:
(+varname)
So, in your case it's:
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
var result = Number(num1) + Number(num2);
convert the strings to floats with parseFloat(string) or to integers with parseInt(string)
If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:
function addStrings(str1, str2){
str1a = str1.split('').reverse();
str2a = str2.split('').reverse();
let output = '';
let longer = Math.max(str1.length, str2.length);
let carry = false;
for (let i = 0; i < longer; i++) {
let result
if (str1a[i] && str2a[i]) {
result = parseInt(str1a[i]) + parseInt(str2a[i]);
} else if (str1a[i] && !str2a[i]) {
result = parseInt(str1a[i]);
} else if (!str1a[i] && str2a[i]) {
result = parseInt(str2a[i]);
}
if (carry) {
result += 1;
carry = false;
}
if(result >= 10) {
carry = true;
output += result.toString()[1];
}else {
output += result.toString();
}
}
output = output.split('').reverse().join('');
if(carry) {
output = '1' + output;
}
return output;
}
You can use this to add numbers:
var x = +num1 + +num2;
try
var x = parseFloat(num1) + parseFloat(num2) ;
or, depending on your needs:
var x = parseInt(num1) + parseInt(num2) ;
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
http://www.crockford.com/
http://javascript.crockford.com/
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
I've always just subtracted zero.
num1-0 + num2-0;
Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.
function sum(){
var x,y,z;
x = Number(document.getElementById("input1").value);
y = Number(document.getElementById("input2").value);
z = x + y;
document.getElementById("result").innerHTML = z ;
}
If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.
const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"
Here, you have two options to do this :-
1.You can use the unary plus to convert string number into integer.
2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc
.
Now I am going to show you here with the help of examples(Find the sum of two numbers).
Using unary plus operator
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
Using parsing approach-
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
You can use parseInt to parse a string to a number. To be on the safe side of things, always pass 10 as the second argument to parse in base 10.
num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
alert(num1 + num2);
Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.
For example
5 - 7.6 = -2.5999999999999996
#cr05s19xx suggested on a duplicate question:
JavaScript is a bit funny when it comes to numbers and addition.
Giving the following
'20' - '30' = 10; // returns 10 as a number
'20' + '30' = '2030'; // Returns them as a string
The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:
function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
Use the parseFloat method to parse the strings into floating point numbers:
parseFloat(num1) + parseFloat(num2)
I use this in my project.I use + sign to treat string as a number (in with_interesst variable)
<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var days = document.getElementById('days').value;
var interest = (amount * (interest_rate * .01)) / days;
var payment = ((amount / days) + interest).toFixed(2);
var with_interest = (amount * (interest_rate * .01));
var with_interesst = (+amount * (interest_rate * .01)) + (+amount);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Target Daily = PHP"+payment;
document.getElementById('with_interesst').innerHTML = "Amount w/Interest = PHP"+with_interesst;
}
</script>
<div name="printchatbox" id="printchatbox">
<form id="Calculate" class="form-horizontal">
<h2>You Can Use This Calculator Before Submit </h2>
<p>Loan Amount: PHP<input id="amount" type="number" min="1" max="1000000" onchange="computeLoan()"></p>
<p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
<p>Term<select id="days" type="number" min="1" max="72" step=".1" onchange="computeLoan()">
<option value="40">40 Days</option>
<option value="50">50 Days</option>
<option value="60">60 Days</option>
<option value="70">70 Days</option>
<option value="80">80 Days</option>
<option value="90">90 Days</option>
<option value="100">100 Days</option>
<option value="120">120 Days</option>
</select>
</p>
<h2 id="payment"></h2>
<h2 id ="with_interesst"></h2>
</form>
</div>
Hope it helps
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
You may use like this:
var num1 = '20',
num2 = '30.5';
alert((num1*1) + (num2*1)); //result 50.5
When apply *1 in num1, convert string a number.
if num1 contains a letter or a comma, returns NaN multiplying by 1
if num1 is null, num1 returns 0
kind regards!!!
Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.
Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />
<input type="button" onclick="call()" value="Add"/>
<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html
Related
This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 4 years ago.
I'm building a percentage calculator to learn JavaScript. Below is my attempt.
One of the functions works just fine (the one that takes the percentage away from the number), but the one that adds the percentage to the number seems to be adding the values like they are a string. I've had a look for solutions and using parseInt() seems to crop up quite a bit but I can't seem to implement it with my present code so I'm hoping someone can help.
function myFunction() {
var per = document.getElementById("input1").value;
var num = document.getElementById("input2").value;
var sum = num / 100 * per;
var output = num - sum;
console.log(output);
document.getElementById("demo").innerHTML = output;
}
function myFunction2() {
var per = document.getElementById("input3").value;
var num = document.getElementById("input4").value;
var sum = num / 100 * per;
var output = sum + num;
console.log(output);
document.getElementById("demo1").innerHTML = output;
}
<section id="number less percentage"></section>
<h1>Number less percentage</h1>
<input id="input2" placeholder="enter the number"></input>
<input id="input1" placeholder="enter percentage of a number"></input>
<button value='send' id="submit" onclick="myFunction()">Click for
result</button>
<p id="demo"></p>
</section>
<section id="number plus percentage"></section>
<h1>Number plus percentage</h1>
<input id="input4" placeholder="enter the number"></input>
<input id="input3" placeholder="enter percentage of a number"></input>
<button value='send' id="submit" onclick="myFunction2()">Click for
result</button>
<p id="demo1"></p>
</section>
JavaScript is a bit funny when it comes to numbers and addition. For example:
'20' - '30' === 10 // `-` always coerces operands to numbers
'20' + '30' === '2030' // `+` with strings is interpreted as concatenation
The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to numbers before proceeding with the addition or subtraction. Your code can be:
function calculate() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
Was using ExtJS for formatting numbers to percentage earlier. Now as we are not using ExtJS anymore same has to be accomplished using normal JavaScript.
Need a method that will take number and format (usually in %) and convert that number to that format.
0 -> 0.00% = 0.00%
25 -> 0.00% = 25.00%
50 -> 0.00% = 50.00%
150 -> 0.00% = 150.00%
You can use Number.toLocaleString():
var num=25;
var s = Number(num/100).toLocaleString(undefined,{style: 'percent', minimumFractionDigits:2});
console.log(s);
No '%' sign needed, output is:
25.00%
See documentation for toLocaleString() for more options for the format object parameter.
Here is what you need.
var x=150;
console.log(parseFloat(x).toFixed(2)+"%");
x=0;
console.log(parseFloat(x).toFixed(2)+"%");
x=10
console.log(parseFloat(x).toFixed(2)+"%");
Modern JS:
For any of these, remove * 100 if you start with a whole number instead of decimal.
Basic
const displayPercent = (percent) => `${(percent * 100).toFixed(2)}%`;
Dynamic with safe handling for undefined values
const displayPercent = (percent, fallback, digits = 2) =>
(percent === null || percent === undefined) ? fallback : `${(percent * 100).toFixed(digits)}%`;
Typescript:
const displayPercent = (percent: number) => `${(percent * 100).toFixed(2)}%`;
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction(num) {
number = num.toString();;
console.log(number)
var words2 = number.split(".");
for (var i = 0; i < words2.length; i++) {
words2[i] += " ";
}
num1 = words2[0];
num2 = words2[1];
num1 = num1.trim();
if(num2==undefined){
number1 = num1+'.00%';
return number1;
}else{
num2 = num2.trim();
number1 = num1+'.'+num2+'%';
return number1;
}
}
document.getElementById("demo").innerHTML = myFunction(50.12);
</script>
</body>
</html>
I had decimal values such as 0.01235 and 0.016858542 that I wanted to convert to percentages 1.235% and 1.6858542% respectively. I thought it was going to be easy, just calculate (0.012858542 * 100) and I'm good to go. I was wrong, (0.012858542 * 100) = 1.2858542000000002 because of decimal conversion.
Let's add toFixed() to the calculation and I end up with the right value.
(0.012858542*100).toFixed(7) // returns "1.2858542"
(0.01235*100).toFixed(7) // returns "1.2350000"
I don't like to show four trailing zeros when they're unnecessary. One solution I thought about was to use replace() to remove all trailing zeros but I ended up using Numeral.js instead because it does all the work for me while it's lightweight. I can recommend it!
import numeral from 'numeral';
numeral(0.012858542 * 100).format('0.00[0000]') // returns "1.2858542"
numeral(0.01235 * 100).format('0.00[0000]') // returns "1.235"
Transform number to percentage with X float decimal positions
function toPercent(number, float) {
var percent = parseFloat(number * 100).toFixed(float) + "%";
return percent;
}
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I have two strings which contain only numbers:
var num1 = '20',
num2 = '30.5';
I would have expected that I could add them together, but they are being concatenated instead:
num1 + num2; // = '2030.5'
How can I force these strings to be treated as numbers?
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
MDN docs for parseInt
MDN docs for parseFloat
In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!
parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)
Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.
http://jsfiddle.net/EtX6G/
var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];
Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);
function Append(text) {
body.appendChild(document.createTextNode(text));
body.appendChild(document.createElement('br'));
}
I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:
(+varname)
So, in your case it's:
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
var result = Number(num1) + Number(num2);
convert the strings to floats with parseFloat(string) or to integers with parseInt(string)
If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:
function addStrings(str1, str2){
str1a = str1.split('').reverse();
str2a = str2.split('').reverse();
let output = '';
let longer = Math.max(str1.length, str2.length);
let carry = false;
for (let i = 0; i < longer; i++) {
let result
if (str1a[i] && str2a[i]) {
result = parseInt(str1a[i]) + parseInt(str2a[i]);
} else if (str1a[i] && !str2a[i]) {
result = parseInt(str1a[i]);
} else if (!str1a[i] && str2a[i]) {
result = parseInt(str2a[i]);
}
if (carry) {
result += 1;
carry = false;
}
if(result >= 10) {
carry = true;
output += result.toString()[1];
}else {
output += result.toString();
}
}
output = output.split('').reverse().join('');
if(carry) {
output = '1' + output;
}
return output;
}
You can use this to add numbers:
var x = +num1 + +num2;
try
var x = parseFloat(num1) + parseFloat(num2) ;
or, depending on your needs:
var x = parseInt(num1) + parseInt(num2) ;
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
http://www.crockford.com/
http://javascript.crockford.com/
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
I've always just subtracted zero.
num1-0 + num2-0;
Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.
function sum(){
var x,y,z;
x = Number(document.getElementById("input1").value);
y = Number(document.getElementById("input2").value);
z = x + y;
document.getElementById("result").innerHTML = z ;
}
If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.
const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"
Here, you have two options to do this :-
1.You can use the unary plus to convert string number into integer.
2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc
.
Now I am going to show you here with the help of examples(Find the sum of two numbers).
Using unary plus operator
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
Using parsing approach-
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
You can use parseInt to parse a string to a number. To be on the safe side of things, always pass 10 as the second argument to parse in base 10.
num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
alert(num1 + num2);
Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.
For example
5 - 7.6 = -2.5999999999999996
#cr05s19xx suggested on a duplicate question:
JavaScript is a bit funny when it comes to numbers and addition.
Giving the following
'20' - '30' = 10; // returns 10 as a number
'20' + '30' = '2030'; // Returns them as a string
The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:
function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
Use the parseFloat method to parse the strings into floating point numbers:
parseFloat(num1) + parseFloat(num2)
I use this in my project.I use + sign to treat string as a number (in with_interesst variable)
<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var days = document.getElementById('days').value;
var interest = (amount * (interest_rate * .01)) / days;
var payment = ((amount / days) + interest).toFixed(2);
var with_interest = (amount * (interest_rate * .01));
var with_interesst = (+amount * (interest_rate * .01)) + (+amount);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Target Daily = PHP"+payment;
document.getElementById('with_interesst').innerHTML = "Amount w/Interest = PHP"+with_interesst;
}
</script>
<div name="printchatbox" id="printchatbox">
<form id="Calculate" class="form-horizontal">
<h2>You Can Use This Calculator Before Submit </h2>
<p>Loan Amount: PHP<input id="amount" type="number" min="1" max="1000000" onchange="computeLoan()"></p>
<p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
<p>Term<select id="days" type="number" min="1" max="72" step=".1" onchange="computeLoan()">
<option value="40">40 Days</option>
<option value="50">50 Days</option>
<option value="60">60 Days</option>
<option value="70">70 Days</option>
<option value="80">80 Days</option>
<option value="90">90 Days</option>
<option value="100">100 Days</option>
<option value="120">120 Days</option>
</select>
</p>
<h2 id="payment"></h2>
<h2 id ="with_interesst"></h2>
</form>
</div>
Hope it helps
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
You may use like this:
var num1 = '20',
num2 = '30.5';
alert((num1*1) + (num2*1)); //result 50.5
When apply *1 in num1, convert string a number.
if num1 contains a letter or a comma, returns NaN multiplying by 1
if num1 is null, num1 returns 0
kind regards!!!
Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.
Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />
<input type="button" onclick="call()" value="Add"/>
<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html
I have number saying 15.67789.
I want to display only two numbers after the decimal point (i.e 15.67) with out doing any rounding on the number.
For Eg:
15.67789.toFixed(2) returns 15.68 instead
I want to display only 15.67.
Using regex:
edit: I modified regex to accept numbers without decimal places and numbers with one decimal place (thanks #Mi-Creativity):
var num = 134.35324;
num.toString().match(/^(\d*(\.\d{0,2})?)/)[0];
Working example https://jsfiddle.net/yevwww8m/2/
Using substr:
var num = 15.67789;
num = num.toString().substr(0,'15.67789'.indexOf('.')+3);
Working example: https://jsfiddle.net/pmmy9o3r/
Just for fun, using regex replace:
var num = 15.57789;
num = num.toString().replace(/^(\d+\.\d{2}).*/g, '$1');
Working example: https://jsfiddle.net/4eq3jd4e/
angular.module('app', [])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app='app'>
<input type='number' ng-model='tex' />
{{tex|number:2}}
</body>
use the number filter to specify the number of digits to be displayed after the decimal point.
Updated
Simply multiply the number by 100 to move the point two decimal places, floor it then divide it by 100
var nums = [15.67789, 101.62, 134.35324, 0.00658853, 0.002422, 4.27, 1.1095];
for (var i = 0; i < nums.length; ++i) {
var temp = nums[i] * 100;
temp = (('' + temp).split('.')[1] !== '99999999999994') ? (Math.floor(temp) / 100) : nums[i];
console.log(temp.toFixed(2));
}
How can I round down a number in JavaScript?
math.round() doesn't work because it rounds it to the nearest decimal.
I'm not sure if there is a better way of doing it other than breaking it apart at the decimal point at keeping the first bit. There must be...
Using Math.floor() is one way of doing this.
More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
Round towards negative infinity - Math.floor()
+3.5 => +3.0
-3.5 => -4.0
Round towards zero can be done using Math.trunc(). Older browsers do not support this function. If you need to support these, you can use Math.ceil() for negative numbers and Math.floor() for positive numbers.
+3.5 => +3.0 using Math.floor()
-3.5 => -3.0 using Math.ceil()
Math.floor() will work, but it's very slow compared to using a bitwise OR operation:
var rounded = 34.923 | 0;
alert( rounded );
//alerts "34"
EDIT Math.floor() is not slower than using the | operator. Thanks to Jason S for checking my work.
Here's the code I used to test:
var a = [];
var time = new Date().getTime();
for( i = 0; i < 100000; i++ ) {
//a.push( Math.random() * 100000 | 0 );
a.push( Math.floor( Math.random() * 100000 ) );
}
var elapsed = new Date().getTime() - time;
alert( "elapsed time: " + elapsed );
You can try to use this function if you need to round down to a specific number of decimal places
function roundDown(number, decimals) {
decimals = decimals || 0;
return ( Math.floor( number * Math.pow(10, decimals) ) / Math.pow(10, decimals) );
}
examples
alert(roundDown(999.999999)); // 999
alert(roundDown(999.999999, 3)); // 999.999
alert(roundDown(999.999999, -1)); // 990
Rounding a number towards 0 (aka "truncating its fractional part") can be done by subtracting its signed fractional part number % 1:
rounded = number - number % 1;
Like Math.floor (rounds towards -Infinity) this method is perfectly accurate.
There are differences in the handling of -0, +Infinity and -Infinity though:
Math.floor(-0) => -0
-0 - -0 % 1 => +0
Math.floor(Infinity) => Infinity
Infinity - Infinity % 1 => NaN
Math.floor(-Infinity) => -Infinity
-Infinity - -Infinity % 1 => NaN
Math.floor(1+7/8)
To round down towards negative infinity, use:
rounded=Math.floor(number);
To round down towards zero (if the number can round to a 32-bit integer between -2147483648 and 2147483647), use:
rounded=number|0;
To round down towards zero (for any number), use:
if(number>0)rounded=Math.floor(number);else rounded=Math.ceil(number);
Was fiddling round with someone elses code today and found the following which seems rounds down as well:
var dec = 12.3453465,
int = dec >> 0; // returns 12
For more info on the Sign-propagating right shift(>>) see MDN Bitwise Operators
It took me a while to work out what this was doing :D
But as highlighted above, Math.floor() works and looks more readable in my opinion.
This was the best solution I found that works reliably.
function round(value, decimals) {
return Number(Math.floor(parseFloat(value + 'e' + decimals)) + 'e-' + decimals);
}
Credit to: Jack L Moore's blog
You need to put -1 to round half down and after that multiply by -1 like the example down bellow.
<script type="text/javascript">
function roundNumber(number, precision, isDown) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = 0;
if (isDown) {
tempNumber = -tempNumber;
roundedTempNumber = Math.round(tempNumber) * -1;
} else {
roundedTempNumber = Math.round(tempNumber);
}
return roundedTempNumber / factor;
}
</script>
<div class="col-sm-12">
<p>Round number 1.25 down: <script>document.write(roundNumber(1.25, 1, true));</script>
</p>
<p>Round number 1.25 up: <script>document.write(roundNumber(1.25, 1, false));</script></p>
</div>
Here is math.floor being used in a simple example. This might help a new developer to get an idea how to use it in a function and what it does. Hope it helps!
<script>
var marks = 0;
function getRandomNumbers(){ // generate a random number between 1 & 10
var number = Math.floor((Math.random() * 10) + 1);
return number;
}
function getNew(){
/*
This function can create a new problem by generating two random numbers. When the page is loading as the first time, this function is executed with the onload event and the onclick event of "new" button.
*/
document.getElementById("ans").focus();
var num1 = getRandomNumbers();
var num2 = getRandomNumbers();
document.getElementById("num1").value = num1;
document.getElementById("num2").value = num2;
document.getElementById("ans").value ="";
document.getElementById("resultBox").style.backgroundColor = "maroon"
document.getElementById("resultBox").innerHTML = "***"
}
function checkAns(){
/*
After entering the answer, the entered answer will be compared with the correct answer.
If the answer is correct, the text of the result box should be "Correct" with a green background and 10 marks should be added to the total marks.
If the answer is incorrect, the text of the result box should be "Incorrect" with a red background and 3 marks should be deducted from the total.
The updated total marks should be always displayed at the total marks box.
*/
var num1 = eval(document.getElementById("num1").value);
var num2 = eval(document.getElementById("num2").value);
var answer = eval(document.getElementById("ans").value);
if(answer==(num1+num2)){
marks = marks + 10;
document.getElementById("resultBox").innerHTML = "Correct";
document.getElementById("resultBox").style.backgroundColor = "green";
document.getElementById("totalMarks").innerHTML= "Total marks : " + marks;
}
else{
marks = marks - 3;
document.getElementById("resultBox").innerHTML = "Wrong";
document.getElementById("resultBox").style.backgroundColor = "red";
document.getElementById("totalMarks").innerHTML = "Total Marks: " + marks ;
}
}
</script>
</head>
<body onLoad="getNew()">
<div class="container">
<h1>Let's add numbers</h1>
<div class="sum">
<input id="num1" type="text" readonly> + <input id="num2" type="text" readonly>
</div>
<h2>Enter the answer below and click 'Check'</h2>
<div class="answer">
<input id="ans" type="text" value="">
</div>
<input id="btnchk" onClick="checkAns()" type="button" value="Check" >
<div id="resultBox">***</div>
<input id="btnnew" onClick="getNew()" type="button" value="New">
<div id="totalMarks">Total marks : 0</div>
</div>
</body>
</html>
Math.round(3.14159 * 100) / 100 // 3.14
3.14159.toFixed(2); // 3.14 returns a string
parseFloat(3.14159.toFixed(2)); // 3.14 returns a number
Math.round(3.14159) // 3
Math.round(3.5) // 4
Math.floor(3.8) // 3
Math.ceil(3.2) // 4