How can I round the number using jQuery?
If the number is 3168 I want to print it as 32.
Or if the number is 5233 the result should be 52.
How can I do that?
Should I use the Math.round function?
Yes, you should use Math.round (after dividing by 100).
jQuery is a library for DOM traversal, event handling and animation built on top of JavaScript. It doesn't replace JavaScript and doesn't reimplement all its basic functions.
var num = 3168;
$('#myElement').text(Math.round(num/100));
I assume you mean divide by 100, then round? Or did you mean to have decimal places? (In which case, remove the /100 portion)
Also, this is just basic JavaScript. As another user mentioned, jQuery is to work with the document itself, not to perform math operations.
And here is a snippet from the jQuery math library1:
(function($){
$.round = Math.round;
})(jQuery);
$.round(3168 / 100) // 32
$.round(5233 / 100) // 52
1 Meant for humor only--this kind of functionality is provided out-of-the-box by JavaScript itself.
<script type='text/javascript'>
function jqROund(a) {
return Math.round(a/100);
}
</script>
<input type='text' id='numba' value='3168'>
<input type='button' onclick="alert( jqRound($('#numba').val() ) );">
The Math.round method does exactly you want and does not only ceil, or floor. It will round it to the nearest Integer.
If you're using the javascript Number object you can use the toFixed() method. I'm assuming those numbers are missing the decimal point. If not, divide by 100 and as above.
You can use this one :) roundMe(1.2345, 4)
function roundMe(n, sig) {
if (n === 0) return 0;
var mult = Math.pow(10, sig - Math.floor(Math.log(n < 0 ? -n: n) / Math.LN10) - 1);
return Math.round(n * mult) / mult;
}
Related
I found a very strange issue, the issue is the ROUND method in PHP and Javascript the calculation results are not the same!?
See the following example:
PHP
echo round(175.5); // 176
echo round(-175.5); // -176
Javascript
console.log(Math.round(175.5)); // 176
console.log(Math.round(-175.5)); // -175 <-why not -176!!??
anyone know why? and how to make Javascript and PHP the same results?
That's not an issue, it is well documented
If the fractional portion is exactly 0.5, the argument is rounded to
the next integer in the direction of +∞. Note that this differs from
many languages' round() functions, which often round this case to the
next integer away from zero, instead (giving a different result in the
case of negative numbers with a fractional part of exactly 0.5).
If you want the same behaviour on Javascript, I would use
var n = -175.5;
var round = Math.round(Math.abs(n))*(-1)
A quick solution is to do the following:
echo round(-175.5, 0, PHP_ROUND_HALF_DOWN); // -175
There are other modes to choose from:
PHP_ROUND_HALF_UP - default
PHP_ROUND_HALF_EVEN
PHP_ROUND_HALF_ODD
See the documentation for more information.
This function will behave the same as in javascript:
function jsround($float, $precision = 0){
if($float < 0){
return round($float, $precision, PHP_ROUND_HALF_DOWN);
}
return round($float, $precision);
}
console.log(Math.round(175.5)); // 176
console.log(Math.round(-175.5)); // -175 <-why not -176!!??
175.5 its round value 176 it's value increasing.
-175.5 round value is -175. Because when I round -175.5 then it also increasing that means -175>-176.
To control it more use ceil and floor for rounding. That way you can choose which way to round
Or... if you wanted JavaScript to behave the same as PHP, use this:
function phpRound(number) {
if(number < 0)
return 0 - Math.round(0 - number);
return Math.round(number);
}
I am trying to Math.floor a scientific notation, but at one point the number gets too big and my current method doesn't work anymore. This is what I am using atm
var nr = (number+"").length - 4;
if( nr > 1 ) {
nr = Math.pow( 10, nr );
number= Math.floor(number/nr)*nr;
number= number.toExponential(3);
}
When it becomes a scientific notation by default, I think that's e20+, than my .length method doesn't work anymore since the length it returns isn't accurate. I can think of a work around, and that's to find out the number after e, and update my nr to Math.floor it properly, but it seems like so much work to do something so simple. Here's an example number 8.420960987929105e+79 I want to turn this into 8.420e+79, is there a way I can Math.floor the third decimal point always, no matter what the number is? As it stands when I use toExponential(3) it always rounds the number. My numbers can get as high as e+200 easily, so I need an easier way of doing what I'm currently doing.
Edit: managed to find a work around that works besides Connor Peet's answer for anyone who wants extra options
var nr = 8.420960987929105e+79+"";
var nr1 = nr.substr(0,4);
var nr2 = nr.substr(4, nr.length);
var finalNr = Number(nr1 + 0 + nr2).toExponential(3);
This way is more of a hack, it adds a 0 after the 4th number so when toExponential rounds it up, it gets 'floored' pretty much.
I wrote a little snippet to round a number to a certain number of significant figures some time ago. You might find it useful
function sigFigs(num, figures) {
var delta = Math.pow(10, Math.ceil(Math.log(num) / Math.log(10)) - figures);
return Math.round(num / delta) * delta;
}
sigFigs(number, 3); // => 8.420e+79
I can't seem to find the correct formula for having two decimal places in my code. Right now, it's rounding to three decimal places when I click on the first option in regards to calculations (not that 3 decimal places means anything. But regardless of the result, it should round to 2 decimal places). This is my last attempt:
$('#a_is_valid').one('click', function(){
if ($('#code_promo').val() == 'promocode')
{$('#gtotal').val($('#gtotal').val()-($('#gtotal').val()-
(($('#gtotal').val()*.75)))).fixed(2);
}
})
Given a number (or string representing a number), why not just do this:
var number;
var output = (Math.round(number * 100) / 100).toFixed(2);
In your case, it looks like you'd want:
$('#a_is_valid').one('click', function(){
if ($('#code_promo').val() == 'promocode')
{$('#gtotal').val((Math.round($('#gtotal').val() * 75) / 100).toFixed(2));
Math.round (appropriately enough) rounds to the nearest integer, so you'll have to do a bit of magic. Multiply by 10^(number of decimal places you want) - in your case, 10^2 or 100, round, and then divide by the same number.
In the example I made specifically for you, you'll notice I multiply by 75: 0.75 * 100.
It might be easiest to see this using a function:
function roundToNPlaces(n, val) {
var multiplier = Math.pow(10, n);
return (Math.round(val * multiplier) / multiplier).toFixed(n);
}
Then you could simply set your gtotal as follows:
$('#gtotal').val(roundToNPlaces(2, $('gtotal').val() * 0.75));
See this FIDDLE.
See:
Math.round NOTE: This documentation provides an implementation similar to (but more complex than) the code I gave. If you copy their entire Decimal rounding example in to your code (before the first time you need to use it), you can then just use Math.round10($('#gtotal').val() * .75, -2);. See http://jsfiddle.net/aW44n/1/
toFixed
For instance, I have float 1.1111111111 and need to get 11111111111 and 10.
I want to avoid functions, which may change part after point as I need it to show metric prefixes.
It may look simple with strings, I am just not sure if it is a proper way in JavaScript.
The modular division operator '%' can be used to get the remainder of a division in JS. This means that if we perform the modular division of a floating point number by 1, we get the value after the decimal point. Further, if we build a loop where we multiply by 10 until there is no longer anything after the decimal point, we can find the smallest power of ten we can multiply the original number by to get an integer.
Example below:
function getE(floatingPointValue)
{
var x = floatingPointValue;
var digitsAfterDecimal = 0;
while(x % 1 != 0)
{
x = x * 10;
digitsAfterDecimal++;
}
return x.toString() + " *10^-" + digitsAfterDecimal;
}
Fiddle: http://jsfiddle.net/L8XtP/2/
Hope this helps!
I'm looking for a way to round up a number to the next closest multiple of 250. So for example if I had the following JS:
var containerHeight = $("#container").height();
...And we imagine the value of "containerHeight" was 680px, I would want a way to round up to 750px (if the value was 1007, it should round up to 1250). I suspect this requires a solution that is more complex than I anticipate. Or perhaps jQuery has a built in function that will make this feasible?
I suppose this is more of a math question than it is a jQuery question (but my jQuery syntax knowledge is also a bit limited :)
Any ideas / bits of help are greatly appreciated,
Thanks!
containerHeight = Math.ceil(containerHeight / 250.0) * 250;
function NearestMultiple(i, j) {
alert(Math.ceil(i/ j) * j);
}
NearestMultiple(1007, 250); //returns 1250
See example at http://jsfiddle.net/SUya9/1/
Or what James said too!
EDIT: I see you wanted to round up all the time...Updated fiddle, but James got her in 1.
simple
var rounded = Math.ceil(value / round) * round;
For those that are working with integers, and want a solution that avoids intermediate floating point, use this:
int roundedUp = alignment * ((value + alignment - 1) / alignment);
or without the division:
int mod = value % alignment;
if (mod > 0)
value += (alignment - mod);