I have a function that returns long numbers. 23.23423423423432
I can strip the decimal places:
function shortNumbers(){
var longNumber = 34.324234234234;
var shortNumber = longNumber.toPrecision(2)
alert("Shorter number is " + shortNumber)
}
Next I want to use map to display the values in an alert:
function collectVideoValues(){
var loopsStr = loops.map(x=>x.start+"AA"+x.end).join('AA');
alert("Video Values are " + videoId + "," +loopsStr );
}
Can I insert toPrecision after loops.map ?
loops.map.toPrecision(2).(x=>x.start+"AA"+x.end).join('AA');
I'd like to solve this in 1 or 2 lines of code without making a second function.
I placed toPrecision after x.start and x.end to strip the decimal places from the number.
function collectVideoValues(){
var loopsStr = loops.map(x=>x.start.toPrecision(2)+"i"+x.end.toPrecision(2)).join('i');
document.getElementById("lesson-code").innerHTML= videoId + "ID"+ loopsStr;
}
Related
This question already has answers here:
Javascript to convert string to number? [duplicate]
(4 answers)
Closed 7 years ago.
I am pretty new in JavaScript and JQuery and I am having a strange behavior with a simple mathematical sum into a JQuery function that retrieve numbers from some input field inside a JSP page (I can't put a JSFiddle because the values are take from jsp model object)
So, this is my JQuery function:
$("#variazioneUlterioreSaldoInput").bind('change keyup', function() {
console.log("VALUE CHANGED !!!");
var ulterioreSaldo = $("#variazioneUlterioreSaldoInput").val(); // Non ha separatori di migliaia o di decimanli quindi non devo eseguire replace
var saldo = $("#saldo").val().replace(/[^0-9,]/g, '').replace(",",".");
var anticipo = $("#anticipo").val().replace(/[^0-9,]/g, '').replace(",",".");
var totalePagamento = ulterioreSaldo + saldo + anticipo;
console.log("ulterioreSaldo: " + ulterioreSaldo );
console.log("ulterioreSaldo type: " + typeof ulterioreSaldo);
console.log("saldo: " + saldo);
console.log("saldo type: " + typeof saldo);
console.log("anticipo: " + anticipo);
console.log("anticipo type: " + typeof anticipo);
console.log("totalePagamento: " + totalePagamento);
console.log("totalePagamento type: " + typeof totalePagamento);
});
that retrieve and sum 3 values obtained from 3 differents input fields.
So for the values retrieved from the input tags having id="saldo" and id="anticipo" I apply a replace with 2 regex because these are strings that represent formatted number so before sum I have to obtain a plain number.
The problem is that when I perform the sum of these values by this line:
var totalePagamento = ulterioreSaldo + saldo + anticipo;
I obtain this wrong outout related to the sum: totalePagamento: 0.010.004499.48, this is the entire log into the FireBug Console.
VALUE CHANGED !!!
ulterioreSaldo: 0.01
ulterioreSaldo type: string
saldo: 0.00
saldo type: string
anticipo: 4499.48
anticipo type: string
totalePagamento: 0.010.004499.48
totalePagamento type: string
As you can see I have also printed the type of the retrieved objects and seems that are String and not Number so when I use the + operator these values are concatenated and not summed.
How can I correctly converts these values into Number and sum it?
Since you are adding decimal numbers try using parseFloat method:
var totalePagamento = parseFloat(ulterioreSaldo) + parseFloat(saldo) + parseFloat(anticipo);
And if you want only 2 digits after decimal use:
totalePagamento.toFixed(2);
use parseFloat() to sum the values
var totalePagamento = parseFloat(ulterioreSaldo) + parseFloat(saldo) + parseFloat(anticipo);
totalePagamento = totalePagamento.toFixed(2); //it will set floating point to 2 values e.g. 40.22
You have to use parseFloat() function to convert string into numbers. The parseFloat() function parses a string argument and returns a floating point number.
$(document).ready(function(){
var ulterioreSaldo = "0.01";
var saldo = "0.0";
var anticipo = "4499.48";
var sum = parseFloat(ulterioreSaldo) + parseFloat(saldo) + parseFloat(anticipo);
alert(sum);
});
Here is a Demo for the same.
I have an issue in doing a simple addition and save the value in a variable.
Basically I have the following code:
var accsen;
var lowsev = parseInt(accsen);
var hisev = parseInt(accsen) + parseInt(0.65);
console.log('Lowsev: ' + lowsev);
console.log('Hisev: ' + hisev + ' Type: ' + typeof(hisev));
console.log('Accsen: ' + accsen);
The variable accsen is being given a value from the database. Lowsev is being assigned the same value as accsen,while hisev is being assigned the value of accsen + 0.65.
However the issue I am having is that both lowsev and hisev are remaining 0. On doing console.log I get these values:
Lowsev: 0
Hisev: 0 Type: undefined
Accsen: 0.75
Can anyone tell me what I am doing wrong in the addition? Am I using the correct operators?
Sounds like you want to use parseFloat instead of parseInt.
"Lowsev is being assigned the same value as accsen" It's not, you're rounding it to an integer.
But parseInt() doesn't round properly. 0.75 comes out as 0, so it's working. Assuming you actually want to round these values try
var accsen;
var lowsev = Math.round(accsen);
var hisev = Math.round(accsen) + Math.round(0.65);
EDIT given the response
Your JS is treating accsen as a string, you need to convert to a number
var accsen = '0.75'; // as other people have noted this val in your code is missing.
var lowsev = parseFloat(accsen);
var hisev = parseFloat(accsen) + 0.65;
I need to grab the elements of some small arrays and put them together to make a bigger array. But I don't want those small arrays to be the elements of the big array. I just need their elements. Then I need to randomly chose ONLY one element from the big array.
Normally the big array will be:
Array.prototype.randomElement = function () {
return this[Math.floor(Math.random() * this.length)]
}
var small_1_array = [1,2,3,4];
var small_2_array = [5,6,7,8,9];
var small_3_array = [10,11,12];
var big_array = [small_1_array, small_2_array, small_3_array];
console.log("big_array is: " + big_array);
Result:
big_array is: 1,2,3,4,5,6,7,8,9,10,11,12
The problem with this way is that I can only choose one of the the small arrays(a group of numbers), but not their elements(only a number). For example:
console.log("a random number from big_array is: " + big_array.randomElement());
Result:
a random number from big_array is: 1,2,3,4
And this is a solution I could think of:
var rearrange_array = (big_array.toString()).split(",");
console.log("rearrange_array is : " + rearrange_array);
Result:
rearrange_array is : 1,2,3,4,5,6,7,8,9,10,11,12
Now if I execute:
console.log("a random number from rearrange_array is: " + rearrange_array.randomElement());
the result would be something like this:
a random number from rearrange_array is: 2
Is there any other way to put some arrays together and be able to call only one element of them?
Just apply your randomElement function twice:
console.log("a random number from one of the arrays is: "
+ big_array.randomElement().randomElement());
Of course you also could put the small arrays together and choose from the new huge one. The method to do that is concatenation:
var rearrange_array = Array.prototype.concat.apply([], big_array);
// or, without the big_array variable:
var rearrange_array = small_1_array.concat(small_2_array, small_3_array);
// then:
return rearrange_array.randomElement();
Use Array.concat, which
Returns a new array comprised of this array joined with other array(s) and/or value(s).
In your case:
var small_1_array = [1,2,3,4];
var small_2_array = [5,6,7,8,9];
var small_3_array = [10,11,12];
var big_array = small_1_array.concat(small_2_array, small_3_array);
console.log("a random number from big_array is: " + big_array.randomElement());
I have a function with info that grabs hours, rates, and then tax deduction and then spits it out. It works fine
var newtax= new Number(dep[i]);
taxrate = newtax*100;
var h=eval(document.paycheck.hours.value);
var r=eval(document.paycheck.payrate.value);
document.paycheck.feedback.value= taxrate + txt;
var total= r*(1-newtax)*h ;
total=total.toFixed(2);
document.paycheck.feedback3.value= ("$ "+ total);
I have to put where it takes the total and puts it in a function to put it only two decimals. It works this way and only does two decimals but i need the decimal conversion in a function. can anyone shed some like .
This is where i cut it to two decimals and i am unable to put in function and then send it back to the feedback3.value.
total=total.toFixed(2);
document.paycheck.feedback3.value= ("$ "+ total);
If you're asking how to write a function that takes a number and formats it as a dollar value with two decimals (as a string) then this would work:
function formatMoney(num) {
return "$ " + num.toFixed(2);
}
// which you could use like this:
document.paycheck.feedback3.value= formatMoney(total);
// though you don't need the total variable (unless you use it elsewhere)
// because the following will also work:
document.paycheck.feedback3.value = formatMoney( r*(1-newtax)*h );
By the way, you don't need eval to get the values from your fields. Just say:
var h = document.paycheck.hours.value;
var r = document.paycheck.payrate.value;
how can I split a number into sub digits. I have a number 20:55 n need to split in to two parts as 20 and 55.
var mynumber = 20:55;
var split = mynumber.toString();
document.write("Hour : " + split[0]);
document.write("Minutes : " + split[1]);
but am getting wrong value after toString() function call.
EDIT: 1 This is what I want. This is working fine but only works with windows. In linux Firefox am not getting the correct value in function .. something like 12.200000000000000001 instead of 12.25
<script type="text/javascript">
var myarray = new Array();
myarray = [[12.25, 1],[13.25,1]];
//alert(myarray[0][0]);
func(myarray[0][0]) ;
function func(n) {
var split = n.split(".");
document.writeln("Number : " + n); // Number : 12.25
document.writeln("Hour : " + split[0]); // Hour : 12
document.writeln("Minutes : " + split[1]); // Minutes : 25
}
</script>
Use split() function
var number_array=mynumber.split(":")
On your example
var mynumber = "20:55";
var split = mynumber.split(":");
document.write("Hour : " + split[0]);
document.write("Minutes : " + split[1]);
More on this
http://www.w3schools.com/jsref/jsref_split.asp
You are using split(), a string function, on a number. Use this:
var split = n.toString().split(".");
Works perfectly on Firefox 3.6.3 (and Opera 10.60, and Chromium 5), Ubuntu Linux 10.04.
Use split function
var numSplit = mynumber.split(':');
Then you can access each value using numSplit[0] and numSplit[1]