How would I add zeros to this jscript when appropriate? [duplicate] - javascript

This question already has answers here:
How to round to at most 2 decimal places, if necessary
(91 answers)
Format number to always show 2 decimal places
(37 answers)
Closed 2 years ago.
I'm a script newb, lets just get that out of the way.
I have a web slider the code is below.
How do I conditionally add zeros? e.g sometimes the result is something like 15.5, I want 15.50. Or alternatively, if the result is 13, I want to add two zeros to make it 13.00.
$('.slider .tooltip-up','#custom-plan').text(e.value/20);
$('.price','#custom-plan').text($(this).data("currency") + e.value/20);
$('.feature1 span','#custom-plan').text(e.value);
$('.feature2 span','#custom-plan').text(e.value*10);
});
cPlan.value = cPlan.data("slider-value");
$('.slider .tooltip','#custom-plan').append('<div class="tooltip-up"></div>');
$('.slider .tooltip-up','#custom-plan').text(cPlan.value/20);
$('.slider .tooltip-inner','#custom-plan').attr("data-unit",cPlan.data("unit"));
$('.slider .tooltip-up','#custom-plan').attr("data-currency",cPlan.data("currency"));
$('.price','#custom-plan').text(cPlan.data("currency") + cPlan.value/20);
$('.feature1 span','#custom-plan').text(cPlan.value);
$('.feature2 span','#custom-plan').text(cPlan.value*98);```

This is a job for .toFixed().
var numb = 15.5
console.log(numb.toFixed(2))
displays 15.50.

Related

Can it be that difficult to generate 10 random numbers, no repeat? [duplicate]

This question already has answers here:
Generate unique random numbers between 1 and 100
(32 answers)
Closed 2 years ago.
I feel like this should be an easy exercise:
1.- Generate 10 random numbers (0-99) and storage in an array.
2.- Numbers should not repeat.
But all the answer I get from the internet are very complicated or excessive long code.
In the code below I already generate the 10 numbers, but they keep repeating. Any ideas?? (i tried If/else but it didn't work) :(
numbers=[]
for(i=0;i<10;i++){
var oneRandomNum = Math.floor(Math.random()*100);
numbers.push(oneRandomNum);
}
console.log(numbers);
Thank you so much!!!!! :)
You can repeatedly add numbers to a Set, and stop when its size reaches 10:
const set = new Set();
while (set.size !== 10) {
set.add(Math.floor(Math.random() * 100));
}
const numbers = [...set];
console.log(numbers);

Getting long decimals from arithmetic operator [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Precise Financial Calculation in JavaScript. What Are the Gotchas?
(8 answers)
Closed 5 years ago.
I have a piece of code that is pulling data from a SharePoint list from I'm using SPServices and this code then pulls from the Spent column and adds up all the numbers and then puts it in an array however I'm getting some weird results.
none of the numbers it pulls through have more than 2 decimal places(it's a finance column) however I'm getting totals like 57062.229999999996 and 151704.58000000002
I've tried using .toFixed(2) on to mynumber and parseFloat(SpentFix)
and then converting back to a number and I get the same results.
Also the reason why I have a .substring(7) is because the spend column is a computed field so when pulling data float,# is a the start of each entry for some reason
if anyone can help that would be great.
var SpentFix = $(this).attr("ows_Spent").substring(7);
if (SpentFix != undefined) {
var mynumber = parseFloat(SpentFix)
SLarray[counter][1] += mynumber;
}

Extra numbers being added when decrementing value from number with JavaScript [duplicate]

This question already has answers here:
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 5 years ago.
I'm trying to decrement "0.01" from a number, it works fine the first time, but when I try to decrement one more time it adds some extra numbers.
Here is my JavaScript code:
function decrement() {
var credits_sidebar = $('#credits_sidebar').html();
var credits_update = credits_sidebar - 0.01;
$("#credits_sidebar").fadeOut('');
$("#credits_sidebar").html(credits_update);
$("#credits_sidebar").fadeIn('');
}
If you click once on the decrement button it works, but if you click another time, the number will be "95.97999999999999" it should be 95.98 instead.
Here's an example JsFiddle:
https://jsfiddle.net/rozvnay1/
var credits_update = (credits_sidebar - 0.01).toFixed(2)
JSFiddle demo: https://jsfiddle.net/8eakhn4L/1/
This is a problem with floating point value representation.
You should consider using
Math.round((credits_sidebar - 0.01)* 100)) / 100
This behavior is normal and expected because of the way floating point math is done in JavaScript.
However what you simply can do is multiply your number by a factor of 100 to make it a whole number that needs to be decremented then you can do the decrement and divide the result by 100 to get the correct decimal answer.
You need to update this for working of code:
var credits_update = (credits_sidebar - 0.01).toFixed(2);

Javascript issue with localstorage (value changing itself) [duplicate]

This question already has answers here:
What is JavaScript's highest integer value that a number can go to without losing precision?
(21 answers)
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 5 years ago.
i'm currently trying to store data via localstorage on my website, and if for example I do so :
localStorage.setItem("vue",10206726906969851)
When I want to get the value back I get this result :
localStorage.getItem("vue")
-> "10206726906969852"
So why does the value changes ? Thank you in advance for your help
JavaScript is not epic at precision with numbers. An example:
.2 + .2 = .4
but
.2 + .2 + .2 = 0.6000000000000001
The number you are using is too big for JS to maintain good precision on it. Log the following in your console and you will see what I mean.
10206726906969851 > Number.MAX_SAFE_INTEGER // returns true
The number you are using is too big. I have experienced this in the past. The server will give me numbers that are fine for Java, but too large for JavaScript. So... JS will mess them all up. The only way to fix was to get a shorter number that JS wouldn't barf on.

Autoload Random Pages [duplicate]

This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Get a random item from a JavaScript array [duplicate]
(13 answers)
Closed 9 years ago.
I have a repeating page loading function here,
<script>
var interval = 5; // in seconds
var pages = [
'http://example.com/index.php',
'http://example.com/about.php',
'http://example.com/services.php',
'http://example.com/portfolio.php',
'http://example.com/career.php',
'http://example.com/contacts.php'
];
var current_page_index = 0;
setInterval(function() {
loadintoIframe('myframe', pages[current_page_index]);
current_page_index = (current_page_index + 1) % pages.length;
}, interval * 1000); // second setInterval param is milliseconds
</script>
Working fine but I would like to change its loading pattern to RANDOM. Now it is loading as it is given in a pattern.I mean it will first load 'http://example.com/index.php' then 'http://example.com/about.php' like that.
How can I add random effect to it? Someone help me pls....
This question is the extension of Load different pages with in a single iframe
Rather than iterating through your page indices, just get
pages[Math.floor(Math.random()*pages.length)]
If you want to avoid duplication, ie. go through the pages in a random order, then keep your current code but - before the setInterval - shuffle the array. Personally I'd use
pages.sort(function(a,b) {return Math.random()-0.5;}); But I know there are picky people out there who will say this isn't "random enough"... -shrugs-

Categories