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.
Related
I'm new to writing JavaScript, I'm trying to convert two values from a string to a number, however, I have tried to doing the following approaches but none seem to work.
Example:
const num = parseInt('100.00') // returns 100
const num = Number('100.00') // returns 100
const num = +'100.00'; // returns 100
I need to return 100.00 as a number I have gone to other similar post they didn't seem to help, all knowledge is appreciated thanks!
In Javascript everything is Number, which is double-precision floating point 64 bit number (=decimal).
100.00 is equal to 100, therefore it shows you 100.
What you are asking is not possible, the decimal 100 is not representable as 100.00 as number, you can only represent it as a String with help of toFixed;
var num = 100;
var strNum = num.toFixed(2); // in this case you have a string instead of a number
console.log(typeof num, num);
console.log(typeof strNum, strNum);
It seems to me that all the approaches you have tried work.
Internally, JavaScript stores all numbers using the floating point format. It uses the minimum number of decimals needed when it displays the value.
This is 0 for integer numbers as 100. 100.00 is still 100, adding any number of 0 after the decimal point doesn't change its value.
The recommended method to parse a string that looks like a number is to use Number.parseInt() or Number.parseFloat().
parseFloat() recognizes only numbers written in base 10 but parseInt() attempts to detect the base by analyzing the first characters of the input string. It automatically recognizes numbers written in bases 2, 8, 10 and 16 using the rules described in the documentation page about numbers. This is why it's recommended to always pass the second argument to parseInt() to avoid any ambiguity.
Regarding your concern, use Number.toFixed() to force its representation using a certain number of decimal digits, even when the trailing digits are 0:
const num = parseInt('100.00');
console.log(num); // prints '100'
console.log(num.toFixed(2)); // prints '100.00'
var randomNumber = (Math.random()*3 + 3.5); randomNumber;
alert(randomNumber)
This piece of code returns a number like
4.589729345235789
I need it to return
4.5
So need it to remove all the numbers after the decimal except the first one, can anyone show me how to do that?
You use Number.prototype.toPrecision() with parameter 2, Number.prototype.toFixed() with parameter 1.
+randomNumber.toPrecision(2);
Alternatively, you can use String.prototype.slice() with parameters 0, 3
+String(randomNumber).slice(0, 3);
If you need to set the amount of decimal places in a number, you can use toFixed(X), where X is the amount of decimal places you want to have.
For example,
4.589729345235789.toFixed(1); would result in 4.6.
Keep in mind, this will convert the number into a string.
If you need absolute accuracy and 4.6 is not good enough for you, see this Stackoverflow post, which has this as a more "accurate" method for your case:
var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
Notice the {0,2} inside of that, which is the range. You can change it to {0,1} in your case.
Regarding the famous issue of 1.01+1.02 which is 2.0300000000000002
one of the workarounds is to use toFixed : e.g.
(1.01+1.02).toFixed(2) --->"2.03"
But I saw a solution with toPrecision
parseFloat((1.01+1.02).toPrecision(10))-->"2.03"
But lets have a look at n in
toFixed(n)
toPrecision(n)
How would I know what is n ?
0.xxxxxxxxxxx
+
0.yyyyyyyyyyyyy
---------------------
0.zzzzzzzzzzzzzzzzzzzzzzzzz
^
|
-----??????------
each number being added can have a different decimal digits...
for example :
1.0002+1.01+1.03333--> 3.0435300000000005
how would I calculate the n here ? what is the best practice for this (specific) issue ?
For addition as in this situation I would check the number of decimal places in each operand.
In the simplest of situations the number of decimal places in the operand with the greatest number of decimal places is the value of n.
Once you have this, use which ever method you like to truncate your value. Then get rid of trailing zeros.
You may encounter trailing zeros in situations such as 1.06 + 1.04, the first step would take you to 1.10 then truncating the zero would give 1.1
In your last example 1.0002+1.01+1.03333 greatest number of decimal places is 5 so you are left with 3.04353 and there are no trailing zeros to truncate.
This returns the expected output:
function add(){
// Initialize output and "length" properties
var length = 0;
var output = 0;
// Loop through all arguments supplied to this function (So: 1,4,6 in case of add(1,4,6);)
for(var i = 0; i < arguments.length; i++){
// If the current argument's length as string is longer than the previous one (or greater than 0 in case of the first argument))
if(arguments[0].toString().length > length){
// Set the current length to the argument's length (+1 is to account for the decimal point taking 1 character.)
length = arguments[0].toString().length +1;
}
// Add the current character to the output with a precision specified by the longest argument.
output = parseFloat((output+arguments[i]).toPrecision(length));
}
// Do whatever you with with the result, here. Usually, you'd 'return output;'
console.log(output);
}
add(); // Returns 0
add(1,2,3); // Returns 6
add(1.01,2.01,3.03); // Returns 6.05
add(1.01,2.0213,3.3333); // Returns 6.3646
add(11.01,2.0213,31.3333); // Returns 44.3646
parseFloat even gets rid of trailing zero's for you.
This function accepts as many numbers as parameters as you wish, then adds these together taking the numbers' string length into account, when adding them. The precision used in the addition is dynamically modified to fit the "currently added" argument's length.
Fiddle
If you're doing calculations, you have a couple of choices:
multiply the numbers by eg 100, to convert to integers, then do the calculations, then convert back again
do the calculations, dont worry about the rounding errors, then round the result at display time
If you're dealing with money/currencies, the first option is probably not a bad option. If you're just doing scientific maths, I would personally not worry about it, and just round the results at display time, eg to 6 significant figures which is the default for my c++ compiler (gcc; not sure if it is in the c++ standards or not, but if you print 1.234567890 in gcc c++, the output is 1.23457, and the problem is avoided)
var a = 216.57421;
a.toPrecision(1); // => '200' because 216 with 1 < 5;
a.toPrecision(2); // => '220' because 216 with 6 >= 5;
a.toFixed(1); // => 216.6 because 7 >= 5;
a.toFixed(2); // => 216.57 because 4 < 5;
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 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)