I get 28.6813276578 when i multiply 2 numbers a and b, how can i make it whole number with less digits
and also, when i multiply again i get results after first reult like 28.681321405.4428.68 how to get only one result ?
<script>
$(document).ready(function(){
$("#total").hide();
$("#form1").submit(function(){
var a = parseFloat($("#user_price").val());
var b = parseFloat($("#selling").val());
var total = a*b;
$("#total").append(total)
.show('slow')
.css({"background":"yellow","font-size":50})
;
return false;
});
});
</script>
You can do several things:
total = total.toFixed([number of decimals]);
total = Math.round(total);
total = parseInt(total);
toFixed() will round your number to the number of decimals indicated.
Math.round() will round numbers to the nearest integer.
parseInt() will take a string and attempt to parse an integer from it without rounding. parseInt() is a little trickier though, in that it will parse the first characters in a string that are numbers until they are not, meaning parseInt('123g32ksj') will return 123, whereas parseInt('sdjgg123') will return NaN.
For the sake of completeness, parseInt() accepts a second parameter which can be used to express the base you're trying to extract with, meaning that, for instance,
parseInt('A', 16) === 10 if you were trying to parse a hexidecimal.
See Math.round(...).
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/round
In addition to the other answers about rounding, you are appending the answer to "total" by using
$("#total").append(total)
You need to replace the previous text rather than appending by using
$("#total").html(total)
Related
I am currently trying to add two decimal places to the end of the number 1000 (I need it to be 1000.00)
I am trying to use: parseFloat(1000).toFixed(2) but it keeps returning a string. When I do parseFloat((1000).toFixed(2)) it returns a number, but gets rid of the decimal places. Is there a way to convert the number 1000 into the number 1000.00 without returning a string?
Try to use .toLocaleString()
var n = 1000;
var nWithZerto = n.toLocaleString("en",{useGrouping: false,minimumFractionDigits: 2});
Since, Javascript treat both integer and, decimal as Number, so it doesn't matter in calculation.
But, if you are printing it then only you require formatting and it can be done as (1000).toFixed(2)-> string.
I am having a little problem with rounding numbers which are brought in from html.
For example a value extracted from <input id="salesValue"> using var salesValue = $("salesValue").val() would give me a text value.
So if I did something like var doubleSalesValue = salesValue + salesValue; , it would return the number as a concatenation instead of summation of the two values.
I could use var doubleSalesValue = salesValue * 2.0; which does return the value which is to multiple decimal places. However, if I did want to use the other method, how can I approach the situation.
What methods do you use? I have created a function which I run on each number where I want to restrict the decimal places along with converting the type to number
function round(number, figure){
return Number(Number(number).toFixed(figure));
}
I have to run Number initially to make sure that the value is converted to type number and has the method toFixed, otherwise it would throw an error here. Then I have to round the number again to the number of decimal places as required by the function, and somehow after running the toFixed method the number would sometimes turn to a string.
So, I decided to run the Number function Number(number).toFixed(figure)
Is there anything else or any different paradigm that you follow?
EDIT: I want to know if what I am doing here is conventional or are there better methods for this in general?
If you want to round it to 2 decimals you can simply do this:
var roundedNum = Math.round(parseFloat(originalNum) * 100) / 100;
Regarding your question:
and somehow after running the toFixed method the number would sometimes turn to a string.
I suggest next time read the dox a bit better https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed which says:
Returns
A string representation of number that does not use exponential
notation and has exactly digits digits after the decimal place. The
number is rounded if necessary, and the fractional part is padded with
zeros if necessary so that it has the specified length. If number is
greater than 1e+21, this method simply calls
Number.prototype.toString() and returns a string in exponential
notation.
There is two value 'a' and 'b'. i need to check a is greater than 'b'
if it is a big value its check the greater values. but here difference only in point values. it ignore point values
var a='20.796';
var b='20.190';
if (parseInt(a) > parseInt(b))
{
alert("function can work");
return false;
}
You parse your numbers as integers. You want rational/real numbers instead. Use parseFloat:
var a = '20.796';
var b = '20.190';
console.log(parseInt(a,10),parseInt(b,10));
console.log(parseFloat(a),parseFloat(b));
Result:
20 20
20.769 20.190
Also, please always use the radix argument if you use parseInt(string [, radix]).
Furthermore - if a and b are numbers, don't save their values in a string. It's much easier to save their values instead:
var a = 20.796;
var b = 20.190;
It's ignoring point values because you are parsing them as integers in the if statement conditional. You have a couple options.
Define the variables as floats instead of strings; remove the parseInt function calls.
Exchange the parseInt for parseFloat calls.
Here, your solution is to parse the strings as floating points rather than integers. For example:
var a = '20.796',
b = '20.190';
if (parseFloat(a) > parseFloat(b)) {
// TODO: .. code ..
}
Your code right now is parsing the strings as integers. Integers are whole number values and CANNOT contain a decimal value, meanwhile floats or floating point numbers CAN contain a decimal value. When you call 'parseInt()' on the floating point, it truncates (or removes) the decimal value and just keeps the whole value. Which is obviously not what you're looking for.
PS: I'm guessing you're new to JavaScript, and so I just want to wish you good luck with learning it. Personnaly, I find JavaScript to be a very beautiful language if you learn it well.
Define your numbers as numbers, and remove the call to parseInt or use parseFloat.
var a=20.796;
var b=20.190;
if (a > b)
{
alert("function can work");
return false;
}
or
if (parseFloat(a) > parseFloat(b))
{
alert("function can work");
return false;
}
I'm trying to insert two numbers in two input type text fields. After I do that, I have to make sure than the first number is smaller than the second. To do this, I'm capturing both fields like this:
var supt = $('#suptotal').val();
var supc = $('#supcubierta').val();
When I compare the two variables, they are strings, so for example 21 is considered bigger than 123.
I've tried to use the function ParseInt, like this
var supt = ParseInt($('#suptotal').val());
but it didn't work. How can I compare the numbers as numbers?
use parseInt($('#suptotal').val(), 10) as against ParseInt($('#suptotal').val(), 10)
The function names are case sensitive
parseInt( $('#suptotal').val(), 10 );
Specify a radix as well, incase the string contains something like '010' which would be interpreted as an octal and result in 8.
ParseInt($('#suptotal').val());
You've written the function incorrectly. parseInt is defined in a lowerCamelCase style.
parseInt($('#suptotal').val());
It is also advised that you specify the radix parameter with 10 for base 10.
parseInt($('#suptotal').val(), 10);
But if you are simply wanting to convert the string into a number, use the unary effect of the binary operator +, which will coerce a value into a number when used on a single operand:
var supt = +$('#suptotal').val();
I have a series of variables that have a decimal point and a few zeros. How do I strip the variable so it goes from 1.000 to 1?
Simply...
Math.round(quantity);
...assuming you want to round 1.7 to 2. If not, use Math.floor for 1.7 to 1.
use parseInt();
parseInt("1.25");//returns 1
parseInt("1.85");//returns 1
parseInt(1.25);//returns 1
parseInt(1.85);//returns 1
Use number = ~~number
This is the fastest substitute to Math.floor()
parseInt is the slowest method
math.floor is the 2nd slowest method
faster methods not listed here are:
var myInt = 1.85 | 0;
myInt = 1;
var myInt = 1.85 >> 0;
myInt = 1;
Speed tests done here:
http://jsperf.com/math-floor-vs-math-round-vs-parseint/2
Use Math.trunc(). It does exactly what you ask. It strips the decimal.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
For rounding numbers to the nearest Integer you can use Math.round() like so:
Math.round("1.000"); // Will produce 1
Math.round(123.4234); // Will produce 123
You don't need jQuery for this.
You can use parseInt just fine. From the page:
document.write(parseInt("10.33") + "<br />"); // 10
Here's another nice example:
I often use Math.round and toLocateString to convert numbers containing decimal places, into a more readable string, with thousand separators:
var myNumberAsString = "1234567.890123" // "1234567.890123"
var myNumber = Math.round(0.0 + myNumberAsString); // 1234568
return myNumber.toLocaleString(); // "1,234,568"
I find this useful when loading decimal values from, say a JSON Web Service, and need to display them in a friendlier format on a web page (when, of course, I don't need to display all of the decimal places).
A faster, more efficient way would be to use JavaScript's bitwise operators, like so:
function stripDecimals(n) {
return n | 0;
}
// examples:
stripDecimals(23.245); // => 23
stripDecimals(100.015020); // => 100
The | (OR operator) will treat the numbers as 32-bit (binary 0s and 1s), followed by returning the desired result depending on the operands, which in this case would result to an integer stripped of all decimal places.
I suggest you use something called Math.trunc()... put your number in the parentheses. The reason I don't suggest you use Math.round() is that it might change the integer part of your decimal number which some people won't want though you can use Math.round() if you know you want to get the closest integer.