On Load I got my input value 5.02, now i need to change in 6.
Now i am getting either null or 5.02.
How i can get my data is 6???
My code is:::
<input type="number" id="rate" class="form-control rate " th:value="${abc.rate}" placeholder="Rate" />
javaScript:::
$(".rate input[type='number']").change(function() {
$("#rate").val(""); //i am reseting the value
rateForA =$('#rate').val(); //but i am getting null
console.log(rateForA);
});
I think this will help you
$('.rate').change(function(){
var Num = parseFloat($(this).val());
console.log(Math.ceil(Num));
});
Try
$("#rate ").change(function() { //target input via ID
//we don't want to reset, we want to change value
var myNumber = parseFloat($('#rate').val()); //get decimal value
var result = myNumber + 0.98; //Add numbers together
//Or, you can round up to the nearest whole number instead of adding the numbers together
//Thanks to #Bilbo Baggins for this method
//var result = Math.ceil(myNumber);
console.log(result); //result should be 6
});
When you use .val, it's returning the value as a string instead of a number(integer) like this: "5.02"
We need it as an integer like so: 5.02 (no quotes)
So, we must then use parseFloat() (since you're using decimal places in your value) to get the value as an integer instead of a string.
We then either add the numbers together or you can remove the addition line and use the round up method instead to get to 6.
Related
I can't seem to figure out why the subtraction is working in my code, but when I change the subtraction sign to an addition sign, I get a console error: Uncaught TypeError: undefined is not a function. Where is the error?
Here is a fiddle with the subtraction: http://jsfiddle.net/c8q7p6ac/
Here is a fiddle with the addition in place of the subtraction sign: http://jsfiddle.net/c8q7p6ac/1/
The subtraction sign and the addition sign are in the variable updatedNumber
HTML:
<div class="amount">$1000.00</div>
<input class="new-number" type="text">
<div class="button">Click</div>
jQuery:
$('.button').on('click', function(){
//get value of input
var newNumber = $('.new-number').val();
//get total number value
var totalNumber = $('.amount').text();
var getNumberOnly = totalNumber.indexOf('$') + 1;
var newTotalNumb = totalNumber.substr(getNumberOnly, totalNumber.length);
//add new number to total number
var updatedNumber = (newTotalNumb + newNumber).toFixed(2);
//and update total
$('.amount').html('$'+updatedNumber);
});
The subtraction works because JavaScript converts them to numbers. However, in case of addition, it converts them to strings as soon as one of the operands is a string.
You need to convert the string to a number:
var updatedNumber = (parseInt(newTotalNumb) + parseInt(newNumber)).toFixed(2);
While dealing with decimal points, you can also use parseFloat which will preserve the decimal points.
Here's the updated fiddle.
I am bewildered as to why I cannot add three numbers together. Here is my HTML:
<div><label>Sales Price: </label>
<input type="number" name="sales_price" value="3">
</div>
<div><label>Incentives: </label>
<input type="number" name="incentives" value="2">
</div>
<div><label>Acquisition Fee: </label>
<input type="number" name="acq_fee" value="1">
Here is my JavaScript:
var salesPrice = document.getElementsByName("sales_price")[0];
var incentives = document.getElementsByName("incentives")[0];
var acqFee = document.getElementsByName("acq_fee")[0];
var netCapCost = salesPrice.value - incentives.value + acqFee.value;
I wanted a simple calculation to be done: (3-2+1) = 2. However, netCapCost returns 11, which is the concatenation of the result of (3-2) and 1. What did I do wrong? Many Thanks in advance!
You need to convert those values into numbers with parseInt() or else the + operator will be interpreted as string concatenation. You are doing
var netCapCost = salesPrice.value - incentives.value + acqFee.value;
Which is
var netCapCost = "3" - "2" + "1"
"3"-"2" will return 1, which is what you want but 1 + "1" will be concatenated into "11" since the right operand is a string. So Number + String -> concatenation
var salesPrice;
var incentives;
var acqFee;
var npc;
function calculate(e) {
var netCapCost = (parseFloat(salesPrice.value) - parseFloat(incentives.value) + parseFloat(acqFee.value)).toPrecision(3);
npc.value = netCapCost;
}
window.onload = function (){
salesPrice = document.getElementsByName("sales_price")[0];
incentives = document.getElementsByName("incentives")[0];
acqFee = document.getElementsByName("acq_fee")[0];
npc = document.getElementsByName("npc")[0];
salesPrice.onchange = calculate;
calculate();
};
Your problem is that text fields value is always of type STRING. When subtracting it forces a conversion to type FLOAT. Then the plus operation shares an opperator with the concatenate operation. So when you have two strings being added it concatenates rather than converting to FLOAT or INT. So basically you have "2"-"1" being converted to 2-1 as strings cannot be subtracted which gives you (1) then you have (1)+"1" which will concatenate rather than add as you have a string. Always use parseFloat or parseInt when expecting numeric data from user entry as it will always be a string when originally submitted.
you are doing a string concatation, all value get from input value are string,
the first calcuation salesPrice.value - incentives.value is currect is becuase, the - sign convert the incentives.value to number
the currect way is
var netCapCost = parseInt(salesPrice.value, 10) - parseInt(incentives.value, 10) + parseInt(acqFee.value, 10);
it's better to use a Math library to do the calcuation in javascript, because sooner or later, you will encounter the problem like 0.3 - 0.2 = 0.09999999
I think confusion here is HTML 5 introduces input type number however javascript engine doesn't introduce support for reading such specific fields. We end up using old traditional way of reading input field value which defaults everything to string.
Only advantage of using number type field would be that you do not have to worry about exception/erroneous situation where number is not being entered.
Other answer suggesting to use parseInt function, is the way to go unless you have luxury of introducing javascript framework like jQuery and use more sophisticated approach for reading it.
Im using the following method to add up text boxes. I have tried changing multiple things and cant seem to multiply two text box values! essential I want 2 text box that values are multiplied and displayed in a third text box. I want this value to be fluid aka change when the number changes! I was using this code because i may be multiplying more then one thing but if this is too much of a hassle i will live with just multiplying two at a time
The code im using to add is
<!--adding script #-->
<script>
$(document).ready(function(){
calculateSum();
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
$("#sum").val(sum.toFixed(2));
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
var total = document.getElementById("subtotal").value == "";
var total = document.getElementById("subtotal").value = sum;
}
<!--END adding script #-->
I tried setting the last line to
var times1 = document.getElementById(subtotal);
var times2 = document.getElementById(tax);
var equal = times1.value * times2.value;
and then changing var total1 = document.getElementById("total1").value = sum9; to var total1 = document.getElementById("total1").value = equal;
The text boxes id are subtotal and tax the box im trying to update is total1.
Thanks alot!
On every keyup, instead of getting all values and adding them explicitly, it is better to deduct the previous value of the corresponding input and add the current updated value to sum..
Also, if subtotal is correctly calculated, then the multipication operation what ever you have done should work correctly..
Please find the following jsfiddle where the sum is calculated as explained above along with multiplying the tax..
http://jsfiddle.net/tgvrs_santhosh/77uxK/1/
Let me know if you still face the issue..
Instead of this
if(!isNaN(this.value) && this.value.length!=0) {
I think a regular expression may work better because you are using string values
if (/^([-]?((\d+)|(\d+\.\d+)|(\.\d+)))$/.test(this.value)) {
I haven't tested this regex, but you should be able to find a good regex to test for valid numbers if this one doesn't work for some reason. Also I noticed you have a == after that getElementById.
I'm not totally certain it matters, but you can do sum += (this.value * 1) instead of parseFloat.
update
Try this var equal = ($("#subtotal").val() * 1) * ($("#tax").val() * 1);
I found your question very confusing, but I think what you're trying to say is you want to add up all the .txt fields to get a sub-total, then multiply that sub-total by a tax rate to get a total. If so, then you already know the sub-total is a valid number due to the way you calculate it, so then:
var tax = +$("#tax").val(), // get tax and convert to a number
total = tax ? sum * tax : sum; // if tax is a non-zero number multiply
// otherwise just take the sum as is
If your tax field is not an input then use .text() instead of .val().
Your existing code is rather more complicated than it needs to be. You can do this:
$(document).ready(function(){
calculateSum();
// you don't need an .each() loop, you can bind a keyup handler
// to all elements in the jQuery object in one step, and you don't
// need the anonymous function since it does nothing but call calculateSum:
$(".txt").keyup(calculateSum);
});
function calculateSum() {
var sum = 0,
val;
//iterate through each textboxes and add the values
$(".txt").each(function() {
// you don't need to test for NaN: just attempt to convert this.value
// to a number with the unary plus operator and if the result is not
// a number the expression val = +this.value will be falsy
if(val = +this.value)
sum += val;
});
$("#sum").html(sum.toFixed(2));
var tax = +$("#tax").val();
$("#total1").html((tax ? sum * tax : sum).toFixed(2));
}
For some reason the unary plus operator used throughout my answer is not widely known, but I prefer it to parseFloat().
I have retrieved a string and I extracted a decimal number from it using regex, e.g. 1.00 or 3.99. Now I wanna use these numbers for calculation. How can I convert those regex results into proper numbers so I can perform calculation? In the code below, every click should add the price to the previous total but it doesn't do the sum of numbers properly.
var SaveAfrica = {
init: function () {
this.addToBasket();
},
addToBasket: function () {
var featured = $('section.featured'),
bsktTotalSpan = $('.basket_total span.basket-qty'),
list = featured.find('ul'),
item = list.find('li');
featured.delegate('.buy-now', 'click', function (e) {
var thisElem = $(this),
qtyData = thisElem.closest('li').data('price'),
total = parseInt(bsktTotalSpan.text()) + parseFloat(qtyData.match(/[\d\.\d]+/i));
e.preventDefault();
bsktTotalSpan.text(parseFloat(total));
console.log('The total is: total);
});
}
};
SaveAfrica.init();
The HTML where the digit is from:
<li data-price="£2.99"><img src="someImage.jpg" alt="some image" /></li>
Many thanks
Your problem may be that .match() returns an array of matches. So you might try something like:
parseFloat(qtyData.match(/[\d\.\d]+/i)[0]);
What does the sum come out to, if anything at all?
You may want to try the following instead:
total = parseFloat(bsktTotalSpan.text()) + parseFloat(qtyData.match(/[\d\.\d]+/i));
That is, parse both of them to floats And explicitly define total as a float. Otherwise, the decimals might be getting truncated somewhere.
I think there is a typo in while getting the price from the element.
The code should be as below,
qtyData = thisElem.closest('li').data('data-price'),
You can simply multiply the string by 1 in order to convert it into a number:
num = '1.00' * 1 //result is the number 1
I have the following code. I would like to have it such that if price_result equals an integer, let's say 10, then I would like to add two decimal places. So 10 would be 10.00.
Or if it equals 10.6 would be 10.60. Not sure how to do this.
price_result = parseFloat(test_var.split('$')[1].slice(0,-1));
You can use toFixed() to do that
var twoPlacedFloat = parseFloat(yourString).toFixed(2)
If you need performance (like in games):
Math.round(number * 100) / 100
It's about 100 times as fast as parseFloat(number.toFixed(2))
http://jsperf.com/parsefloat-tofixed-vs-math-round
When you use toFixed, it always returns the value as a string. This sometimes complicates the code. To avoid that, you can make an alternative method for Number.
Number.prototype.round = function(p) {
p = p || 10;
return parseFloat( this.toFixed(p) );
};
and use:
var n = 22 / 7; // 3.142857142857143
n.round(3); // 3.143
or simply:
(22/7).round(3); // 3.143
To return a number, add another layer of parentheses. Keeps it clean.
var twoPlacedFloat = parseFloat((10.02745).toFixed(2));
If your objective is to parse, and your input might be a literal, then you'd expect a float and toFixed won't provide that, so here are two simple functions to provide this:
function parseFloat2Decimals(value) {
return parseFloat(parseFloat(value).toFixed(2));
}
function parseFloat2Decimals(value,decimalPlaces) {
return parseFloat(parseFloat(value).toFixed(decimalPlaces));
}
ceil from lodash is probably the best
_.ceil("315.9250488",2)
_.ceil(315.9250488,2)
_.ceil(undefined,2)
_.ceil(null,2)
_.ceil("",2)
will work also with a number and it's safe
You can use .toFixed() to for float value 2 digits
Exampale
let newValue = parseFloat(9.990000).toFixed(2)
//output
9.99
I have tried this for my case and it'll work fine.
var multiplied_value = parseFloat(given_quantity*given_price).toFixed(3);
Sample output:
9.007
parseFloat(parseFloat(amount).toFixed(2))
You have to parse it twice. The first time is to convert the string to a float, then fix it to two decimals (but the toFixed returns a string), and finally parse it again.
Please use below function if you don't want to round off.
function ConvertToDecimal(num) {
num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
alert('M : ' + Number(num)); //If you need it back as a Number
}
For what its worth: A decimal number, is a decimal number, you either round it to some other value or not. Internally, it will approximate a decimal fraction according to the rule of floating point arthmetic and handling. It stays a decimal number (floating point, in JS a double) internally, no matter how you many digits you want to display it with.
To present it for display, you can choose the precision of the display to whatever you want by string conversion. Presentation is a display issue, not a storage thing.
#sd
Short Answer: There is no way in JS to have Number datatype value with trailing zeros after a decimal.
Long Answer: Its the property of toFixed or toPrecision function of JavaScript, to return the String. The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype. So to achieve the above in JS we have 2 options
Either use data as a string or
Agree to have truncated value with case '0' at the end ex 2.50 -> 2.5.
You can store your price as a string
You can use
Number(string)
for your calculations.
example
Number("34.50") == 34.5
also
Number("35.65") == 35.65
If you're comfortable with the Number function , you can go with it.
Try this (see comments in code):
function fixInteger(el) {
// this is element's value selector, you should use your own
value = $(el).val();
if (value == '') {
value = 0;
}
newValue = parseInt(value);
// if new value is Nan (when input is a string with no integers in it)
if (isNaN(newValue)) {
value = 0;
newValue = parseInt(value);
}
// apply new value to element
$(el).val(newValue);
}
function fixPrice(el) {
// this is element's value selector, you should use your own
value = $(el).val();
if (value == '') {
value = 0;
}
newValue = parseFloat(value.replace(',', '.')).toFixed(2);
// if new value is Nan (when input is a string with no integers in it)
if (isNaN(newValue)) {
value = 0;
newValue = parseFloat(value).toFixed(2);
}
// apply new value to element
$(el).val(newValue);
}
Solution for FormArray controllers
Initialize FormArray form Builder
formInitilize() {
this.Form = this._formBuilder.group({
formArray: this._formBuilder.array([this.createForm()])
});
}
Create Form
createForm() {
return (this.Form = this._formBuilder.group({
convertodecimal: ['']
}));
}
Set Form Values into Form Controller
setFormvalues() {
this.Form.setControl('formArray', this._formBuilder.array([]));
const control = <FormArray>this.resourceBalanceForm.controls['formArray'];
this.ListArrayValues.forEach((x) => {
control.push(this.buildForm(x));
});
}
private buildForm(x): FormGroup {
const bindvalues= this._formBuilder.group({
convertodecimal: x.ArrayCollection1? parseFloat(x.ArrayCollection1[0].name).toFixed(2) : '' // Option for array collection
// convertodecimal: x.number.toFixed(2) --- option for two decimal value
});
return bindvalues;
}
I've got other solution.
You can use round() to do that instead toFixed()
var twoPlacedFloat = parseFloat(yourString).round(2)
The solution that work for me is the following
parseFloat(value)