trim to 2 decimals - javascript

I have:
onclick="document.getElementById('field1').value =
Math.round((parseFloat(document.getElementById('field2').value,2)*100))/100 +
Math.round((parseFloat(document.getElementById('field3').value,2)*100))/100;"
Most numbers round ok to 2 decimal points which is what I need.
However, with an example like
onclick="document.getElementById('field1').value =
Math.round((parseFloat(document.getElementById('21.29').value,2)*100))/100 +
Math.round((parseFloat(document.getElementById('54.70').value,2)*100))/100;"
Field 1 is returning 75.99000000000001 How can I trim to 75.99 consistently?

var num = 5 / 6;
var display = num.toFixed(2)
num outputs: 0.8333333333333334
display outputs: "0.83"

How about this:
parseFloat(document.getElementById('21.29').toFixed(2));
The toFixed method should take care of the rounding nicely for you.

Use the method toFixed(2) to fix it at 2 decimal places:
(Math.round((parseFloat(document.getElementById('21.29').value,2)*100))/100 +
Math.round((parseFloat(document.getElementById('54.70').value,2)*100))/100).toFixed(2);

I had a similar issue - where I do not wanted to round the value but trim upto 2 decimals
I got the perfect solution for by writing this function and using where ever needed to trim upto 2 decimals
function upto2Decimal(num) {
if (num > 0)
return Math.floor(num * 100) / 100;
else
return Math.ceil(num * 100) / 100;
}
if you call
upto2Decimal(2.3699) or upto2Decimal(-2.3699)
// returns 2.36 or -2.36
check this solution using your JS console of the browser

You can use :
function myFunction()
{
var num = "-54.987656";
var roundedValue = roundMethod(num,5);
document.getElementById("demo").innerHTML = roundedValue;
}
function roundMethod(numberVal, roundLimit) // This method will not add any additional 0, if decimal places are less than the round limit
{
var isDecimal = numberVal.indexOf(".") != -1;
if(isDecimal)
{
if(numberVal.split(".")[1].length > roundLimit)
{
return parseFloat(numberVal).toFixed(roundLimit).toString();
}else
{
return numberVal;
}
}else
{
return numberVal;
}
}
<html>
<body>
<p>Click the button to display the fixed number.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>

Related

JavaScript Math Object: Negative , Zero and Positive Value [duplicate]

This question already has answers here:
Generating random whole numbers in JavaScript in a specific range
(39 answers)
Closed 5 years ago.
I want to random a numbers like this from -5....0....5.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 7-1);
}
</script>
</body>
</html>
In this case it returns only -1. It is possible to do in javascript math object?
You could use a factor of 11 (this returns a value of 0 ... 10) and adjust the number by -5.
console.log(Math.floor(Math.random() * 11) - 5);
Try this may this works (There you can give a range also to the random number)...
<button onclick="getRandomInt(-5,5)">Try it</button>
<p id="demo"></p>
<script>
function getRandomInt(min, max) {
document.getElementById("demo").innerHTML = Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>
REF Link
In this case it returns only -1. It is possible to do in javascript
math object?
You need to use brackets (), in your case it resulted in Math.floor(Math.random() * 7-1 ) => Math.floor(0.xxx-1 ) => Math.floor(-0.xxx ) => -1
Make it
Math.floor(Math.random() * (7-1) );
I want to random a numbers like this from -5....0....5.
First get a number between 0 and 5
Math.floor(Math.random() * (5-0) );
Then multiply the same by either 1 or -1 randomly
var value = Math.floor(Math.random() * (5-0) );
var sign = window.performance.now() % 2 == 1 ? 1 : -1; //get the current timestamp of the system in nanoseconds (something like 1512635632715) and checking if that number is even or odd
value *= sign ;
Added Demo with nano seconds instead of milliseconds
function generateRandom() {
var value = Math.floor(Math.random() * (5 - 0));
var sign = window.performance.now() % 2 == 1 ? 1 : -1;
value *= sign;
return value;
}
var arr = [];
for( var counter = 0; counter < 100; counter++)
{
arr.push(generateRandom());
}
console.log(arr);

Rounding issue in Math.round() & .toFixed()

I used below two methods :
Number.prototype.myRound = function (decimalPlaces) {
var multiplier = Math.pow(10, decimalPlaces);
return (Math.round(this * multiplier) / multiplier);
};
alert((239.525).myRound(2));
Mathematically alert should be 239.53 but its giving 239.52 as output.
So i tried using .toFixed() function & i got proper answer.
But when i try to get answer for 239.575 it gives again wrong output.
alert((239.575).toFixed(2));
Here output should be 239.58 instead its giving 239.57.
This error creating a bit difference in final output. So can anyone help me to sort this out?
This method will give very correct round result.
function RoundNum(num, length) {
var number = Math.round(num * Math.pow(10, length)) / Math.pow(10, length);
return number;
}
Just call this method.
alert(RoundNum(192.168,2));
Internally, 239.575 cannot be represented exactly. In binary, 0.575 would be something like 1/2 + 1/16 + 1/128 + 1/256 + ....
It just so happens that, represented in binary, the result is slightly less than 239.575. Therefore, Math.round rounds down.
To demonstrate, try this:
alert(239.575 - 239.5)
You would expect the result to be 0.075, but instead you get 0.07499999999998863.
Just use Math.round
function round(figureToRound){
var roundOff = Math.round((figureToRound* 100 ).toFixed(2))/100;
return roundOff;
}
console.log(round(1.005));
This will help the rounding off issue completely.
round() will do the trick.Try This:
var v= Math.round(239.575 * 100) / 100;
alert(v);
Working FIddle
The problem is probably floating point inaccuracy, thus you might get different results in different cases (different gathering of a number, different browsers etc.).
See also this: toFixed(2) rounds "x.525" inconsistently?
In my software I use this:
(require DecimalJS)
Number.prototype.toFixed = function(fixed) {
return (new Decimal(Number(this))).toFixed(parseFloat(fixed) ||
0);
};
var x = 1.005;
console.log( x.toFixed(2) ); //1.01
function bestRound(val, decimals){
decimals = decimals || 2;
var multiplier = Math.pow(10, decimals)
return Math.round((val * multiplier ).toFixed(decimals)) / multiplier;
}
bestRound(239.575 - 239.5) 0.08
bestRound(239.575) 239.58
bestRound(239.525) 239.53
bestRound(1.005) 1.01
I got this to simply overwrite it ->
Number.prototype.toFixed = function(fractionDigits, returnAsString = true) {
var digits = parseInt(fractionDigits) || 0;
var num = Number(this);
if( isNaN(num) ) {
return 'NaN';
}
var sign = num < 0 ? -1 : 1;
if (sign < 0) { num = -num; }
digits = Math.pow(10, digits);
num *= digits;
//num = Math.round(num.toFixed(12));
num = Math.round( Math.round(num * Math.pow(10,12)) / Math.pow(10,12) );
var ret = sign * num / digits;
return (returnAsString ? ret.toString() : ret ); // tofixed returns as string always
}

How do I zero-fill a number?

I have a working decimal to binary converter, but I want it to ALWAYS show 8 digits,
so if I put in 3 it will say '00000011' and not '11'
Anyone a clue how this can be done?
my code:
<script type="text/javascript">
function ConvertToBinary(dec) {
var bits = [];
var dividend = dec;
var remainder = 0;
while (dividend >= 2) {
remainder = dividend % 2;
bits.push(remainder);
dividend = (dividend - remainder) / 2;
}
bits.push(dividend);
bits.reverse();
return bits.join("");
}
<input type="text" id="txtDec" maxlength="3"/>
<input type="button" value="Convert" onclick="document.getElementById('spBin').innerHTML=ConvertToBinary(document.getElementById('txtDec').value);" />
<span id="spBin"></span>
JavaScript already makes the conversion for you, from a number, using toString method, because you can specify the radix (see the link above):
var n = 13;
console.log(n.toString(2)) // "1101"
If you want add lead zero, in case less then 8, you could have:
var bits = n.toString(2);
console.log("00000000".substr(bits.length) + bits);
With just one method call.
Edit: this answer was written in 2013, nowadays the method padStart can be used instead for the padding:
console.log(n.toString(2).padStart(8, "0"));
How about this:
return String('000000000' + bits.join("")).slice(-8);
Demo (change "dividend" to try with different numbers)
Basically adds 8 zeros to the left and then removes anything more than 8 characters long from the left.
How about before bits.reverse(); You do a while loop like this:
while(bits.length < 8){
bits.push(0);
}
Here's an example solution that will left-pad a number with zeros
#param "num" the number to be left-padded with zeros
#param "width" the number of characters required as a result
#return String the left-padded number
function zeroFill(num, width) {
str = String((new Array(width+1)).join('0') + num).slice(-width)
return str
}
There are other solutions which use a loop to create the zeros.

JavaScript math, round to two decimal places [duplicate]

This question already has answers here:
How to round to at most 2 decimal places, if necessary
(91 answers)
Closed 5 years ago.
I have the following JavaScript syntax:
var discount = Math.round(100 - (price / listprice) * 100);
This rounds up to the whole number. How can I return the result with two decimal places?
NOTE - See Edit 4 if 3 digit precision is important
var discount = (price / listprice).toFixed(2);
toFixed will round up or down for you depending on the values beyond 2 decimals.
Example: http://jsfiddle.net/calder12/tv9HY/
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
Edit - As mentioned by others this converts the result to a string. To avoid this:
var discount = +((price / listprice).toFixed(2));
Edit 2- As also mentioned in the comments this function fails in some precision, in the case of 1.005 for example it will return 1.00 instead of 1.01. If accuracy to this degree is important I've found this answer: https://stackoverflow.com/a/32605063/1726511 Which seems to work well with all the tests I've tried.
There is one minor modification required though, the function in the answer linked above returns whole numbers when it rounds to one, so for example 99.004 will return 99 instead of 99.00 which isn't ideal for displaying prices.
Edit 3 - Seems having the toFixed on the actual return was STILL screwing up some numbers, this final edit appears to work. Geez so many reworks!
var discount = roundTo((price / listprice), 2);
function roundTo(n, digits) {
if (digits === undefined) {
digits = 0;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
var test =(Math.round(n) / multiplicator);
return +(test.toFixed(digits));
}
See Fiddle example here: https://jsfiddle.net/calder12/3Lbhfy5s/
Edit 4 - You guys are killing me. Edit 3 fails on negative numbers, without digging into why it's just easier to deal with turning a negative number positive before doing the rounding, then turning it back before returning the result.
function roundTo(n, digits) {
var negative = false;
if (digits === undefined) {
digits = 0;
}
if (n < 0) {
negative = true;
n = n * -1;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
n = (Math.round(n) / multiplicator).toFixed(digits);
if (negative) {
n = (n * -1).toFixed(digits);
}
return n;
}
Fiddle: https://jsfiddle.net/3Lbhfy5s/79/
If you use a unary plus to convert a string to a number as documented on MDN.
For example:+discount.toFixed(2)
The functions Math.round() and .toFixed() is meant to round to the nearest integer. You'll get incorrect results when dealing with decimals and using the "multiply and divide" method for Math.round() or parameter for .toFixed(). For example, if you try to round 1.005 using Math.round(1.005 * 100) / 100 then you'll get the result of 1, and 1.00 using .toFixed(2) instead of getting the correct answer of 1.01.
You can use following to solve this issue:
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2');
Add .toFixed(2) to get the two decimal places you wanted.
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2').toFixed(2);
You could make a function that will handle the rounding for you:
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
Example:
https://jsfiddle.net/k5tpq3pd/36/
Alternative
You can add a round function to Number using prototype. I would not suggest adding .toFixed() here as it would return a string instead of number.
Number.prototype.round = function(decimals) {
return Number((Math.round(this + "e" + decimals) + "e-" + decimals));
}
and use it like this:
var numberToRound = 100 - (price / listprice) * 100;
numberToRound.round(2);
numberToRound.round(2).toFixed(2); //Converts it to string with two decimals
Example
https://jsfiddle.net/k5tpq3pd/35/
Source: http://www.jacklmoore.com/notes/rounding-in-javascript/
To get the result with two decimals, you can do like this :
var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;
The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result.
The best and simple solution I found is
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // 1.01
try using discount.toFixed(2);
I think the best way I've seen it done is multiplying by 10 to the power of the number of digits, then doing a Math.round, then finally dividing by 10 to the power of digits. Here is a simple function I use in typescript:
function roundToXDigits(value: number, digits: number) {
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
Or plain javascript:
function roundToXDigits(value, digits) {
if(!digits){
digits = 2;
}
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
A small variation on the accepted answer.
toFixed(2) returns a string, and you will always get two decimal places. These might be zeros. If you would like to suppress final zero(s), simply do this:
var discount = + ((price / listprice).toFixed(2));
Edited:
I've just discovered what seems to be a bug in Firefox 35.0.1, which means that the above may give NaN with some values.
I've changed my code to
var discount = Math.round(price / listprice * 100) / 100;
This gives a number with up to two decimal places. If you wanted three, you would multiply and divide by 1000, and so on.
The OP wants two decimal places always, but if toFixed() is broken in Firefox it needs fixing first.
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388
Fastest Way - faster than toFixed():
TWO DECIMALS
x = .123456
result = Math.round(x * 100) / 100 // result .12
THREE DECIMALS
x = .123456
result = Math.round(x * 1000) / 1000 // result .123
function round(num,dec)
{
num = Math.round(num+'e'+dec)
return Number(num+'e-'+dec)
}
//Round to a decimal of your choosing:
round(1.3453,2)
Here is a working example
var value=200.2365455;
result=Math.round(value*100)/100 //result will be 200.24
To handle rounding to any number of decimal places, a function with 2 lines of code will suffice for most needs. Here's some sample code to play with.
var testNum = 134.9567654;
var decPl = 2;
var testRes = roundDec(testNum,decPl);
alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);
function roundDec(nbr,dec_places){
var mult = Math.pow(10,dec_places);
return Math.round(nbr * mult) / mult;
}

Round just decimal in Javascript

I have a value like that:
20.93
I'd like to round it to
20.90
How can I do that in Javascript ?
Thanks!
Multiply the number by 10, round it and then divide the number by 10:
var result = Math.round(20.93 * 10) / 10
I think this should work:
number.toFixed(1);
var num= 20.93
num = Math.floor(num * 10) / 10; // 20.9
num = Math.ceil(num * 10) / 10; //21
I take it that you want the trailing zero. None of the answers give you that. It has to be a String to have the trailing zero.
function my_round(x){
return Number(x).toFixed(1) + '0';
}
If you don't care about the trailing zero and you want a Number (not String), then here's another way to round to decimal places in JavaScript. This rounds to decimal place d.
function my_round(x, d){
return Number( Number(x).toFixed(d) );
}
You would do
my_round('20.93', 1);
or
my_round(20.93, 1);
You can set toFixed(1). but set value = 20.96 then you have 21 and not 20.90;
BUT with my function always will be 20.90 than 20.93 like 20.98/97/96/95...
<script>
var num = 20.93;
function vround(num) { // CREATE BY ROGERIO DE MORAES
var Dif = (num.toFixed(2)-num.toFixed(1)).toFixed(2);
Dif = Dif * 100;
if(Dif <= -1) {
var n = num.toFixed(2) - 0.05;
vround(n);
} else {
var n = num.toFixed(1)+0;
console.log(n);
}
}
vround(num);
</script>
I create this function for get you value, but can change, if you wanna more forms.

Categories