I need some help with dividing a number(currency) by a divisor so I end up with even parts, and any cents left over needs to be divided also.
So for an example 500/9 = 55.55555555555556, that's 55.55 with 0.05 left over to be divined among the first 5 results.
I would like to end up with
55.56
55.56
55.56
55.56
55.56
55.55
55.55
55.55
55.55
This is a similar solution that i found divide number with decimals javascript
but this one adds the change to the last result.
var mathjunk = 500/9;
var formattedtotal = Math.floor(mathjunk*100)/100;
var realtotal = formattedtotal * 9;
var modulus = 500 - realtotal;
var diff = modulus / 5;
var first5 = formattedtotal+diff;
alert("first 5 get $"+first5+", everyone else gets $"+formattedtotal)
this is more of a math question than a programming one.. https://jsfiddle.net/ttz0jsgr/
take a look
function distribute(money, piles){
var m = money * 100,
n = m % piles,
v = Math.floor( m / piles ) / 100,
w = Math.floor( m / piles + 1 ) / 100;
for(var i=0, out = new Array(piles); i < piles; ++i){
out[i] = i<n? w: v;
}
return out;
}
var arr = distribute(500, 9);
var sum = arr.reduce((a,b) => a+b);
Related
How do I get the number of zero decimals behind the comma (but not the total)? So to illustrate an example:
0.00001 > 4
0.000015 > 4
0.0000105 > 4
0.001 > 2
I am looking for methods that are efficient (meaning that they optimize the calculation time).
You can use logarithms to find the magnitude of the number:
var x = 0.00195;
var m = -Math.floor( Math.log(x) / Math.log(10) + 1);
document.write(m); // outputs 2
Later versions of JavaScript have Math.log10, so it would be:
var x = 0.00195;
var m = -Math.floor( Math.log10(x) + 1);
document.write(m); // outputs 2
How using the base-10 logarithm of the numbers works:
x
Math.log10(x)
Math.floor(Math.log10(x) + 1 )
0.1
-1
0
0.01
-2
-1
0.015
-1.8239…
-1
0.001
-3
-2
0.00001
-5
-4
0.000015
-4.8239…
-4
0.0000105
-4.9788…
-4
Use a regex to match the number of zeros after a decimal point and then count them.
var zeros = float.toString().match(/(\.0*)/)[0].length - 1;
DEMO
Use this one:
function numberOfZeros(n) {
var c = 0;
while (!~~n) {
c++;
n *= 10;
}
return c - 1;
}
document.write(numberOfZeros(0.00065));
This code does the following: it multiplies the number by ten as long as it can be truncated to something not equal 0. The truncation operator "~~" is very performant, because it works with byte representation of the number directly.
It doesn't use any string operations and does exactly what you want: counts the zeros.
//my answer
function t1()
{
var num = 0.0000005323;
numOfZeroes = 0;
while(num < 1)
{
numOfZeroes++;
num *= 10;
}
}
//others
//Andrew Morton's answer
//https://stackoverflow.com/a/31002148/1115360
function t2()
{
var num = 0.0000005323;
var m = -Math.floor( Math.log10(num) + 1);
}
//Amy's Answer
//https://stackoverflow.com/a/31002087/4801298
function t3()
{
var r = 0.0000005323;
var count=0;
var splited = r.toString().split(".")[1];
for(var i=0;i<splited.length;i++)
{
if(splited[i]==0)
{
count++;
}
else
{
break;
}
}
}
//Ted's Answer
//https://stackoverflow.com/a/31002052/4801298
function t4()
{
var number = 0.0000005323;
var numberAsString = number.toString();
var decimalsAsString = numberAsString.substr(numberAsString.lastIndexOf('.')+1);
var leadingZeros = decimalsAsString.substr(0, decimalsAsString.lastIndexOf('0')+1).length;
}
//Bartłomiej Zalewski's answer
//https://stackoverflow.com/a/31001998/4801298
function t5()
{
var n = 0.0000005323;
var c = 0;
while (!~~n) {
c++;
n *= 10;
}
return c - 1;
}
//Andy 's answer
//https://stackoverflow.com/a/31002135/4801298
function t6()
{
var float = 0.0000005323;
var zeros = float.toString().match(/(\.0*)/)[0].length - 1;
}
//Praveen's answer
//https://stackoverflow.com/a/31002011/4801298
function t7()
{
var a = 0.0000005323;
return (a.toString().replace("0.", "").split("0").length - 1);
}
//benchmark function
function bench(func)
{
var times = new Array();
for(var t = 0; t < 100; t++)
{
var start = performance.now();
for(var i = 0; i < 10000; i++)
{
func();
}
var end = performance.now();
var time = end - start;
times.push(time);
}
var total = 0.0;
for(var i=0, l=times.length; i<l; i++)
total += times[i];
var avg = total / times.length;
return avg;
}
document.write('t1: ' + bench(t1) + "ms<BR>");
document.write('t2: ' + bench(t2) + "ms<BR>");
document.write('t3: ' + bench(t3) + "ms<BR>");
document.write('t4: ' + bench(t4) + "ms<BR>");
document.write('t5: ' + bench(t5) + "ms<BR>");
document.write('t6: ' + bench(t6) + "ms<BR>");
document.write('t7: ' + bench(t7) + "ms<BR>");
Note:
This would only work with numbers less than 1 of course. Otherwise, just remove numbers left of the decimal point first, like
num -= num % 1;
need to compare this to another way.
a while later...
I would like a better way to bench these function though. I might have my calculation wrong. I'm adding other peoples answers into the test. I'm now attempting to use the performance API
a bit later than before
AHA! Got it working. Here are some comparisons for you.
You can use something like this:
function num (a) {
return (a.toString().replace("0.", "").split("0").length - 1)
}
Here is a working example (a bit lengthy for clarity):
var number = 0.0004342;
var numberAsString = number.toString();
var decimalsAsString = numberAsString.substr(numberAsString.lastIndexOf('.')+1);
var leadingZeros = decimalsAsString.substr(0, decimalsAsString.lastIndexOf('0')+1).length;
// leadingZeros == 3
Convert the number in to a string and split it with the dot (.). Using the for loop to count the zeros occurrences.
var r = 0.0000107;
var count=0;
var splited = r.toString().split(".")[1];
for(var i=0;i<splited.length;i++)
{
if(splited[i]==0)
{
count++;
}
else
{
break;
}
}
console.log(count);
Node.js 9.0.0
I was looking for a solution without converting or the O(n) approach. Here is what solution I made by O(1).
Part of finding decimal by log – caught from #AndrewMorton, but it might be laggy with the divider: log(10) – 2.302585092994046.
Example
const normalize = (value, zeroCount) => {
const total = 10 ** zeroCount
const zeros = Math.floor(-Math.log10(value / total))
return value * (10 ** zeros)
}
Usage
normalize(1510869600, 13) // 1510869600000
normalize(1510869600, 10) // 1510869600
I'm trying to make a text field so that if there's a number 153.254, that becomes 153.25. And if the field contains 154.2, an extra 0 is added to fill two spots after decimal; 154.20.
toFixed() works great but I don't want the number rounded. Also came across other solutions where if I'm typing in 1.40, then if I move the cursor back after 1, I can't type anything in unless I clear the field and start over.
Is there a simple jQuery way to limit two characters after a decimal, and then if there's only one character after the decimal, add a zero to fill the two character limit?
(The field may receive value from database that's why the second part is required)
Solution Update: For those interested, I put this together to achieve what I wanted (Thanks to answers below and also other questions here on stackoverflow)
$('.number').each(function(){
this.value = parseFloat(this.value).toFixed(3).slice(0, -1);
});
$('.number').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(3).slice(0, -1);
}
}
return this; //for chaining
});
you could do myNumber.toFixed(3).slice(0, -1)
try this:
var num = 153.2
function wacky_round(number, places) {
var h = number.toFixed(2);
var r = number.toFixed(4) * 100;
var r2 = Math.floor(r);
var r3 = r2 / 100;
var r4 = r3.toFixed(2);
var hDiff = number - h;
var r4Diff = number - r3;
var obj = {};
obj[hDiff] = h;
obj[r4Diff] = r4;
if (r4Diff < 0) {
return h;
}
if (hDiff < 0) {
return r4;
}
var ret = Math.min(hDiff, r4Diff);
return obj[ret];
}
alert(wacky_round(num, 2))
How about
function doStuff(num){
var n = Math.floor(num * 100) / 100,
s = n.toString();
// if it's one decimal place, add a trailing zero:
return s.split('.')[1].length === 1 ? (s + '0') : n;
}
console.log(doStuff(1.1), doStuff(1.111)); // 1.10, 1.11
http://jsfiddle.net/NYnS8/
I am trying to find an algorithm to result:
45 => 100
458 => 1000
8456 => 10000
I would like to "round" this way, i looked into Math.round() but it doesn't think to be enough.
For a single line of code you can do what Rup said. A base 10 log will give you the closest power of 10, then do ten to the power of the ceiling of the result of the log
var x = 45;
Math.pow(10, Math.ceil(Math.log(x) / Math.LN10));
easiest thing to come up with without thinking:
var n = 455;
var rounded;
for(var i = 1000000000 i>= 1; i/=10)
{
if(i < n)
{
break;
}
else
{
rounded = i;
}
}
I have a value like that:
20.93
I'd like to round it to
20.90
How can I do that in Javascript ?
Thanks!
Multiply the number by 10, round it and then divide the number by 10:
var result = Math.round(20.93 * 10) / 10
I think this should work:
number.toFixed(1);
var num= 20.93
num = Math.floor(num * 10) / 10; // 20.9
num = Math.ceil(num * 10) / 10; //21
I take it that you want the trailing zero. None of the answers give you that. It has to be a String to have the trailing zero.
function my_round(x){
return Number(x).toFixed(1) + '0';
}
If you don't care about the trailing zero and you want a Number (not String), then here's another way to round to decimal places in JavaScript. This rounds to decimal place d.
function my_round(x, d){
return Number( Number(x).toFixed(d) );
}
You would do
my_round('20.93', 1);
or
my_round(20.93, 1);
You can set toFixed(1). but set value = 20.96 then you have 21 and not 20.90;
BUT with my function always will be 20.90 than 20.93 like 20.98/97/96/95...
<script>
var num = 20.93;
function vround(num) { // CREATE BY ROGERIO DE MORAES
var Dif = (num.toFixed(2)-num.toFixed(1)).toFixed(2);
Dif = Dif * 100;
if(Dif <= -1) {
var n = num.toFixed(2) - 0.05;
vround(n);
} else {
var n = num.toFixed(1)+0;
console.log(n);
}
}
vround(num);
</script>
I create this function for get you value, but can change, if you wanna more forms.
In math how do I obtain the closest number of a number that is divisible by 16?
For example I get the random number 100 and I want to turn that number (using a math function) into the closest number to 100 that is divisible by 16 (In this case its 96)
I'm trying to do this in JavaScript but if I knew the math formula for it I would easily do it in any language.
Thank you,
Regards
Generate a random integer. Multiply it by 16.
Divide by 16, round, and multiply by 16:
n = Math.round(n / 16) * 16;
function GetRandomNumberBetween(lo, hi) {
return Math.floor(lo + Math.random() * (hi - lo));
}
Number.prototype.FindClosestNumberThatIsDivisibleBy = function(n) {
return Math.round(this / n) * n; //simplify as per Guffa
/* originally:
var c = Math.ceil(n);
var f = Math.floor(n);
var m = num % n;
var r = f * n;
if (m > (n / 2))
r = c * n;
return r;
*/
};
var r = GetRandomNumberBetween(10, 100);
var c = r.FindClosestNumberThatIsDivisibleBy(16);
function closest(n) {
var r = 0, ans = 0;
r = n % 16
if r < 8 {
ans = n - r
} else {
ans = n + (16 - r)
}
return ans;
}
Here's how I understand your question. You're given a number A, and you have to find a number B that is the closest possible multiple of 16 to A.
Take the number given, "A" and divide it by 16
Round the answer from previous step to the nearest whole number
multiply the answer from previous step by 16
there's the pseudocode, hope it's what you're looking for ;-)
A general JS solution
var divisor = 16;
var lower = 0;
var upper = 100;
var randDivisible = (Math.floor(Math.random()*(upper-lower))+lower)*divisor;
alert(randDivisible);