Remove numbers after decimal in javascript - javascript

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.

Related

Parsefloat with 2 decimals without losing function to do equations (not as string)

I've seen multiple topics regarding this question, but none seem to answer it.
I want to round a number to two decimals, but without losing the function to use it in equations. So it shouldn't be transformed to a string. This DOES NOT work for what I want: parseFloat("50").toFixed(2)
Does anyone know how to parseFloat with 2 decimals as a number?
Just parse it back to a float.
parseFloat(Number(1.2345).toFixed(2)); //1.23
In javascript a number cannot have trailing zeros. 2.5 is a correct but 2.50 is not, this is why toFixed returns a string, not a number.
The best way to handle what you need is to store the number as a number and let it round out to whatever it needs. Only when showing the number on the screen should you do the toFixed(2) method to transforms it into a string.
// js
const price = 7.999999
const reducedPrice = price * 0.8
const finalReductionPrice = reducedPrice / 2.666666
// html
<p>price {price.toFixed(2)</p>
<p>reducedPrice {reducedPrice.toFixed(2)</p>
<p>finalReductionPrice {finalReductionPrice.toFixed(2)</p>

Rounding a figure retrieved from html using javascript and jquery

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.

whole number in javascript?

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)

round in javascript stuck me

hello I want to round an amount in javascript but unable to do and totally stuck.
My scenario is, I have a base amount and marukup % on base. On the basis of these two I want to calculate total amount. I have calculated the amount but i want to round the result.
I have used following formula
amount=base+((base/100)*markup
This formula always give me result without decimal point. I want to get exact amount upto two decimal points. I have used math.round like this
amount=math.round(base+((base/100)*markup).toFixed(2)
but it always return result without decimal point. For example my base value is 121 and markup is 5%. The amount should be 127.05 . But above formula always returns 127. Any guidelines?
I'm pretty sure math.round returns an integer. Even if you round it then, it'll just be 127.00 anyway.
Here's the correct solution(but it isn't easy):
Do not use non-integer values for money!
It doesn't work.
Use an integer in cents.
That is, instead of 127, keep 12700 in your app.
That way all roundings should work fine.
The toFixed(n) function rounds the Number to n decimals, there is no need to use Math.round at all. Try:
total = function (base, markup) { return (base + (base * markup / 100)); };
amount = total(121,5).toFixed(2);
Note that amount will be typeof String and not Number.
This should work:
amout = (Math.round((base*(1+markup))*100)/100).toFixed(2)
By the way, i was using markup as 5/100...
Sound like a integer division problem to me. I'd guess that javascript is seeing the 100 as an int.
Try this:
amount=(base+((base/100.toFixed(2))*markup).toFixed(2)

strip decimal points from variable

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.

Categories