Rounding Column Footer in Datatables [duplicate] - javascript

How will i round margin_total to 3 decimal places?
margin_total = margin_total + parseFloat(marginObj.value);
document.getElementById('margin_total').value = margin_total;

Use num.toFixed(d) to convert a number into the String representation of that number in base 10 with d digits after the decimal point, in this case,
margin_total.toFixed(3);

The toFixed() method converts a number into a string, keeping a specified number of decimals. A string representation of input that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.
function myFunction() {
var num = 5.56789;
var n = num.toFixed(3)
document.getElementById("demo").innerHTML = n;
}
<p>Click the button to display the fixed number.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

const roundedDown = Math.round(6.426475 * 1000) / 1000
console.log(roundedDown)
const roundedUp = Math.round(6.426575 * 1000) / 1000
console.log(roundedUp)
The above code rounds to 3 decimal places (dp)
To round to 2 dp use 100 instead of 1000 (all occurrences)
To round to 4 dp use 10000 instead of 1000
You get the idea!

const num = 70.012345678900
console.log(parseFloat(num.toFixed(3)));
// expected output: 70.012

Related

how to get exact two digits after decimal point in jquery or javascript

I want the exact 2 digits after the decimal point. I tried the toFixed(2) function but it returns rounded off 2 digits. Here is my Code it returns 18.70 but I want 18.69extract number
rim_weight = (23* 36 *70);
rim_weight = rim_weight/3100; // retuns 18.69677419354839
rim_weight = rim_weight.toFixed(2); // returns 18.70
If you just want to truncate the number to two decimal places, first divide by 31, convert to an integral value using Math.floor and then divide by 100:
rim_weight = (23 * 36 * 70);
rim_weight = Math.floor(rim_weight / 31);
rim_weight = rim_weight / 100;
console.log(rim_weight);
just convert it to string then match the number up to the second place

How to round up last digit in two decimal point using JavaScript

I want to round up last digit of two decimal point if last digit more then 5.
For example,
2.58 to 2.60
Besides that, I also want to round down last digit of two decimal point if last digit less then 5.
For example, 6.54 to 6.50
How to do this by using javascript
You can achieve this by Math.round and then dividing the result by 10 (which results in an extra 0 in a floating point number:
let number = 2.58;
let rounded = Math.round(number * 10, 2) / 10; // 2.60
let number2 = 2.54;
let rounded2 = Math.round(number2 * 10, 2) / 10; // 2.50
Use the toFixed() method.
var number = 2.58;
var rounded = number.toFixed(1);
console.log(parseFloat(rounded).toFixed(2));

How to get numbers with precision without round up or round down [duplicate]

This question already has answers here:
Truncate (not round off) decimal numbers in javascript
(32 answers)
Closed 8 years ago.
Im trying to get a number with precision to 2 decimals, for example this is what I want, if I have the numbers:
3.456 it must returns me 3.45
3.467 = 3.46
3.435 = 3.43
3.422 = 3.42
I don't want to round up or down or whatever just to get the numbers I see 2 places after .
Thanks
Okay, here is the answer
var a = 5.469923;
var truncated = Math.floor(a * 100) / 100; // = 5.46
Thanks everyone for helping.
Assuming Positive Numbers:
The code:
function roundDown(num,dec) {
return Math.floor(num*Math.pow(10,dec))/Math.pow(10,dec);
}
The test:
function test(num, expected) {
var val = roundDown(num,2);
var pass = val === expected;
var result = pass ? "PASS" : "FAIL";
var color = pass ? "GREEN" : "RED";
console.log("%c" + result + " : " + num + " : " + val, "background-color:" + color);
}
test(3.456, 3.45);
test(3.467, 3.46);
test(3.435, 3.43);
test(3.422, 3.42);
Basic idea:
Take number
Multiply the number to move decimal place to number of significant figures you want
Floor the number to remove the trailing numbers
Divide number back to get the correct value
If you want to have a trailing zero, you need to use toFixed(2) which will turn the number to a string.
function roundDown(num,dec) {
return Math.floor(num*Math.pow(10,dec))/Math.pow(10,dec).toFixed(2);
}
and the test cases would need to change to
test(3.456, "3.45");
test(3.467, "3.46");
test(3.435, "3.43");
test(3.422, "3.42");
Another option is a regular expression.
function roundDown(num,dec) {
var x = num.toString().match(/(\d*(\.\d{2}))?/);
return x ? parseFloat(x[0]) : "";
//return x ? parseFloat(x[0]).toFixed(2) : "";
}
Use String operation to achieve it.
var n = 4.56789;
var numbers = n.toString().split('.');
result = Number(numbers[0]+"."+numbers[1].substr(0,2));
alert(result);
Fiddle
You are looking at the number as if it were a string of digits, rather than a single value, so treat it like a string.-
function cutoff(n, cut){
var parts= String(n).split('.'), dec= parts[1];
if(!cut) return parts[0];
if(dec && dec.length>cut) parts[1]= dec.substring(0, cut);
return parts.join('.');
}
var n= 36.938;
cutoff(n,2)
/* returned value: (String)
36.93
*/
If you want a number, +cutoff(n,2) will do.
function truncateDec(num, decplaces) {
return (num*Math.pow(10,decplaces) - num*Math.pow(10,decplaces) % 1)/Math.pow(10,decplaces);
}
alert(truncateDec(105.678, 2)); // Returns 105.67
alert(truncateDec(105.678, 1)); // Returns 105.6
This could be simplified further if you do not require a dynamic number of decimal places
function truncateDec(num) {
return (num*100 - num*100 % 1)/100;
}
alert(truncateDec(105.678)); // Returns 105.67
How does it work?
The concept is that the main truncation works by getting the remainder from dividing the original decimal by 1. The remainder will be whatever is in the decimals places. The remainder operator is %
105.678 % 1 = 0.678
By subtracting this remainder from the original number, we will be left with only the integer.
105.678 - 0.678 = 105
To include x number of decimal places, we need to first multiply the original number by 10 to the power of that number of decimal places, thereby shifting the decimal backward by x positions. In this example, we will take x = 2.
105.678 * 10^2
= 105.678 * 100
= 10567.8
Now, we repeat the same procedure by subtracting the remainder again.
10567.8 % 1 = 0.8
10567.8 - 0.8 = 10567
And to return back to the number of places as requested, we divide it back by 10^x
10567 / 10^2
= 10567 / 100
= 105.67
Hope it helps!

Opposite of toString(36)?

var a = (123.456).toString(36) //"3f.gez4w97ry0a18ymf6qadcxr"
Now, how do I revert back to the original number using that string?
Note: parseInt(number,36) only works for integers.
You could try parsing the integer and float parts separately with parseInt, as parseFloat does not support a radix:
function parseFloatInBase(n, radix) {
var nums = n.split(".")
// get the part before the decimal point
var iPart = parseInt(nums[0], radix)
// get the part after the decimal point
var fPart = parseInt(nums[1], radix) / Math.pow(radix, nums[1].length)
return iPart + fPart
}
// this will log 123.456:
console.log(parseFloatInBase("3f.gez4w97ry0a18ymf6qadcxr", 36))
I am dividing by radix ^ numLength because I am basically moving the decimal point over numLength spaces. You would do this just like in math class, because as you know dividing by 10 moves the decimal over one space, because most math is in base 10. Example:
123456 / 10 / 10 / 10 = 123.456
This is equivalent to
123456 / (10 * 10 * 10) = 123.456
And therefore
123456 / (10 ^ 3) = 123.456

How can I round down a number in Javascript?

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

Categories

Resources