round up nearest 0.10 - javascript

I need to round up to the nearest 0.10 with a minimum of 2.80
var panel;
if (routeNodes.length > 0 && (panel = document.getElementById('distance')))
{
panel.innerHTML = (dist/1609.344).toFixed(2) + " miles = £" + (((dist/1609.344 - 1) * 1.20) + 2.80).toFixed(2);
}
any help would be appreciated

var number = 123.123;
Math.max( Math.round(number * 10) / 10, 2.8 ).toFixed(2);

If you need to round up, use Math.ceil:
Math.max( Math.ceil(number2 * 10) / 10, 2.8 )

Multiply by 10, then do your rounding, then divide by 10 again
(Math.round(12.362 * 10) / 10).toFixed(2)
Another option is:
Number(12.362.toFixed(1)).toFixed(2)
In your code:
var panel;
if (routeNodes.length > 0 && (panel = document.getElementById('distance')))
{
panel.innerHTML = Number((dist/1609.344).toFixed(1)).toFixed(2)
+ " miles = £"
+ Number((((dist/1609.344 - 1) * 1.20) + 2.80).toFixed(1)).toFixed(2);
}
To declare a minimum, use the Math.max function:
var a = 10.1, b = 2.2, c = 3.5;
alert(Math.max(a, 2.8)); // alerts 10.1 (a);
alert(Math.max(b, 2.8)); // alerts 2.8 because it is larger than b (2.2);
alert(Math.max(c, 2.8)); // alerts 3.5 (c);

This is a top hit on google for rounding in js. This answer pertains more to that general question, than this specific one. As a generalized rounding function you can inline:
const round = (num, grainularity) => Math.round(num / grainularity) * grainularity;
Test it out below:
const round = (num, grainularity) => Math.round(num / grainularity) * grainularity;
const test = (num, grain) => {
console.log(`Rounding to the nearest ${grain} for ${num} -> ${round(num, grain)}`);
}
test(1.5, 1);
test(1.5, 0.1);
test(1.5, 0.5);
test(1.7, 0.5);
test(1.9, 0.5);
test(-1.9, 0.5);
test(-1.2345, 0.214);

var miles = dist/1609.344
miles = Math.round(miles*10)/10;
miles = miles < 2.80 ? 2.80 : miles;

to round to nearest 0.10 you can multiply by 10, then round (using Math.round), then divide by 10

Round to the nearest tenth:
Math.max(x, 2.8).toFixed(1) + '0'
Round up:
Math.max(Math.ceil(x * 10) / 10, 2.8).toFixed(2)

Related

Custom Rounding up to nearest 0.05

I want to do custom round up to near 0.05 , based on following condition.It is hard to explain , but following example will be easy to understand .
12.910 - 12.90
12.920 - 12.90
12.930 - 12.90
12.940 - 12.90
12.941 - 12.95
12.950 - 12.95
12.960 - 12.95
12.970 - 12.95
12.980 - 12.95
12.990 - 12.95
12.991 - 13.00
13.000 - 13.00
I tried several function , but it is rounding up 12.98 to 13.00.
function customRound( num) {
return Math.round(num * 20) / 20;
}
Coming at this visually, your rounding algorithm seems to look like this:
The dot is where you want to round to for that interval. ( marks the open end of an interval, ] the closed end. (12.99 belongs to the red interval.) We'll implement this algorithm by manipulating the line to match Math.floor's.
First, let's work with integers.
num * 100
Your rounding interval is left-open and right-closed, but Math.floor is left-closed and right-open. We can flip the line to match by multiplying by −1:
num * 100 * -1
⇒ num * -100
Your rounding intervals' lengths are 5, so we need to put the ends of the intervals on multiples of 5...
num * -100 - 1
...before dividing by 5 to match Math.floor.
(num * -100 - 1 ) / 5
⇒ num * -20 - 0.2
Now we can take the floor.
return Math.floor(num * -20 - 0.2);
Scale back up to the original by multiplying by 5:
return Math.floor(num * -20 - 0.2) * 5;
Shift the returned value over to the dot by adding 4:
return Math.floor(num * -20 - 0.2) * 5 + 4;
Undo the alignment we did earlier:
return Math.floor(num * -20 - 0.2) * 5 + 4 + 1;
⇒ return Math.floor(num * -20 - 0.2) * 5 + 5;
Undo the flip:
return (Math.floor(num * -20 - 0.2) * 5 + 5) * -1;
⇒ return Math.floor(num * -20 - 0.2) * -5 - 5;
And divide the whole thing by 100 to get your original scale back:
return (Math.floor(num * -20 - 0.2) * -5 - 5) / 100;
⇒ return Math.floor(num * -20 - 0.2) * -0.05 - 0.05;
Using Robin Zigmond's testing framework,
function customRound(num) {
return Math.floor(num * -20 - 0.2) * -0.05 - 0.05;
}
// test desired results
var tests = [12.91, 12.92, 12.93, 12.94, 12.941, 12.95, 12.96, 12.97, 12.98, 12.99, 12.991, 13];
for (var i=0; i<tests.length; i++) {
console.log(`${tests[i].toFixed(3)} - ${customRound(tests[i]).toFixed(2)}`);
}
If you really intended to round everything within < .01 of the nearest .05 then try the below, to get the precision of the number it uses answer from Is there a reliable way in JavaScript to obtain the number of decimal places of an arbitrary number?
function decimalPlaces(n) {
var s = "" + (+n);
var match = /(?:\.(\d+))?(?:[eE]([+\-]?\d+))?$/.exec(s);
if (!match) { return 0; }
return Math.max(
0, // lower limit.
(match[1] == '0' ? 0 : (match[1] || '').length)
- (match[2] || 0));
}
var test = 12.941;
var factor = Math.pow(10,decimalPlaces(test));
var remainder = ((test * factor) % (.05 * factor))/factor;
var result;
if (remainder>.04) {
result = Math.round(test*20)/20;
} else {
result = (test*factor - remainder*factor)/factor;
}
console.log('result is:',result);
As far as I can tell from your example, the desired behaviour appears to be "round up to the nearest 0.01, then round that result down to the nearest 0.05".
This can be implemented as follows. As you can see, it agrees exactly with your examples (I even took care to format it the same way) - but please let me know if I've got the wrong end of the stick.
function customRound(num) {
var intermediateResult = Math.ceil(num*100)/100;
return Math.floor(intermediateResult*20)/20;
}
// test desired results
var tests = [12.91, 12.92, 12.93, 12.94, 12.941, 12.95, 12.96, 12.97, 12.98, 12.99, 12.991, 13];
for (var i=0; i<tests.length; i++) {
console.log(`${tests[i].toFixed(3)} - ${customRound(tests[i]).toFixed(2)}`);
}

How can I calculate my odds of x happening?

What is the percent change of this code reaching the number 200, 500 and 1000?
I created this code for 200 to be 50% but it keeps rolling numbers above 200, someone please help me if you understand :D.
var mainMultplier = 100;
var numerator = 99;
var denominator = 100;
for(;;) {
var randomInt = random.real(0, 1.0);
if ( numerator/denominator > randomInt ) {
numerator = numerator + 1;
denominator = denominator + 1;
mainMultplier = mainMultplier + 1;
} else {
break;
}
}
Edit
Based on the code you have posted, we can see these two base rules:
P(100) = 1 - 0.99 = 0.01
P(101) = (1 - P(100)) * (1 - (100 / 101)) = P(101) = (1 - P(100)) * (1 / 101)
The second rule can be generalized for any number X after 100:
P(X) = (1 - P(X - 1)) * (1 / X)
Now, I did learn how to do proofs by induction at Uni, which I'm sure would help my explanation here, but I can't remember it anymore :(. So instead, I've written some code to generate a lookup table p, from 100 to 1000:
var p = [];
p[100] = 0.01;
for (var x = 101; x <= 1000; x++)
p[x] = (1 - p[x - 1]) * (1 / x);
Edit 2
And that's as far as my help can go. You may want to post the generalized algorithm on the Software Engineering page.

How do you make a variable have a 50 percent chance of being one value and 50 percent chance of being another?

a = document.getElementById("find").value
if (a == 'Spark' || a == 'Fire') {
var monster = x
var player = y
var damage = Math.floor(Math.random() * 25)
var damageplayer = Math.floor(Math.random() * 30)
alert('Your squad succeeded the enemy has ' + (x = x - damage) + ' original territories!');
alert ('You have' + (y = y - damageplayer) + 'original territories!'); }
This is my code above I'm trying to make it so that it is a 50/50 chance whether damage will = Math.Floor(math.random () *25) or = 0 . I tried multiplying a math .random by 1 then math. random by 25 and didn't work. How do you make it so 50 percent of the time it will equal 0 and the other 50 percent of the time equal math.random * 25?
Here's one way:
var coin = function() {
return (Math.random() < 0.5 ? 0 : 1);
}
var damage = 25*coin();
Sometimes I wonder how random Math.random really is...
An alternative:
return (new Date().getMilliseconds() % 2);
Don't use floor() as it will always round down. Use round()
var zeroOrOne = Math.round(Math.random());
var damage = zeroOrOne * Math.floor(Math.random() * 25);
Or, if you are one of those "cram as much code into one line as possible" folks:
var damage = Math.round(Math.random()) * Math.floor(Math.random() * 25);
damage = (Math.random() < 0.5) ? 0 : (Math.random() * 25);
Try with
var aux = Math.random()
if (aux < 0,5){
aux = 0
}else{
aux = damage
}
Then you can use the var aux for ur porpose instead of damage
I found a way:
Math.random();
if(Math.random() >= 0.5){ \\set variable to value A }
else { \\set variable to value B }
Since Math.random will randomly select a number 0 to 1 I set the check halfway, at 0.5.

Math.random() applied as a percentage?

so I have this code that is giving me a random number for both top and left attribute of some images.
var random1 = Math.ceil(Math.random() * 500);
var random2 = Math.ceil(Math.random() * 500);
$(document).ready(function () {
$('#randomp').css('top', random1);
$('#randomp').css('left', random2);
});
The problem is that I would be prefer to randomize a number between 1 and 100%. Is that possible?
Math.floor(Math.random() * 100) + 1 + '%'
Since Math.random returns number that is random, not less than 0 and less than 1, you have just to multiply result by 99 instead of 500 to get a number beetween 1 and 100%.
Finally, the code should be as follows:
var random1 = Math.round(Math.random() * 99) + 1;
var random2 = Math.round(Math.random() * 99) + 1;
This gives you a number between 0 and 100 (both included):
Math.floor(Math.random() * 101);
Math random will give you a number between 0 (included) and 1 (excluded)
If you multiply that number with 101, it will give you a number between 0 (included) and 101 (excluded)
Math.floor will return the the largest integer less than or equal to the above number.
Not sure if you want it rounded or not, so here's both:
console.log( rando(1, 100) + "%" );
console.log( rando(1, 100, "float") + "%" );
<script src="https://randojs.com/1.0.0.js"></script>
This uses randojs.com to make the randomness simple and readable. If you need to know more, check out the website.

How do I subtract a percentage from a number in a string?

var valueInString = "2383";
How do I subtract 35% from number and put it back in the variable?
valueInString = valueInString - 35%
Something like the above?
If I understand you correctly, you want to subtract 35% of valueInString from valueInString. So it is just some basic math.
var valueInString = "2383";
var num = parseFloat(valueInString);
var val = num - (num * .35);
console.log(val);
Math:
valueInString = valueInString * (1 - 0.35);
Shorter:
valueInString *= 1 - 0.35;
A nice little utility function for this would be:
const percentageOff = (
price: number,
percentageValue: number
): number => {
return price * (1 - percentageValue / 100)
}
percentageOff(100, 50); // Output: 50
valueInString = valueInString - ((valueInString * 35) / 100);

Categories