numeral.js - negative number rounding/formatting issue - javascript

I'm getting formatting issues with numeral.js when rounding to the nearest negative 100th.
Thoughts on why it's putting the zero before the dollar sign for the zero value?
FIDDLE
var num1 = numeral(-0.006).format('$0,0.00');
var num2 = numeral(-0.002).format('$0,0.00');
document.getElementById("num1").innerHTML = num1;
document.getElementById("num2").innerHTML = num2;

Could be a bug in numeral.js. Regardless, if this is what you are attempting to do, you can drop your dependency for numeral.js and just use plain Javascript Math and toLocaleString() to deal with this.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
https://jsfiddle.net/qL41jg1x/
function toUSCurrency(x) {
var n = Math.round(x*100)/100
return n.toLocaleString(
'en-US' ,
{
style: 'currency' ,
currency: 'USD' ,
minimumFractionDigits: 2 ,
maximumFractionDigits: 2
}
) ;
}
document.getElementById("num1").innerHTML = toUSCurrency(-0.006);
document.getElementById("num2").innerHTML = toUSCurrency(-0.002);
document.getElementById("num3").innerHTML = toUSCurrency(-10000000.002);
document.getElementById("num4").innerHTML = toUSCurrency(10000000.002);
NOTES:
1) Math.round() can get into the floating point nature of numbers if you have to deal with very large decimals.
2) toLocaleString() seems to be supported by all current major browsers. https://caniuse.com/#feat=internationalization

Related

javaScript Rounding decimals using toFixed

I am facing an issue with rounding decimals in JavaScript using toFixed.
const num1 = (100.555).toFixed(2) // "100.56"
const num2 = (10.555).toFixed(2) // "10.55"
Can any one explain why this behavior happens? Why first example round the decimals to 56 while the second one turn it to 55?
Update:
If i add 4 decimals then rounding is differnt.
const num3 = (10.5555).toFixed(2) // "10.56"
This should fix your problem
// its a rounding bug it can be compenstated by representing numbers exactly in decimal notation.
Number.prototype.toFixedDown = function(digits) {
var re = new RegExp("(\\d+\\.\\d{" + digits + "})(\\d)"),
m = this.toString().match(re);
return m ? parseFloat(m[1]) : this.valueOf();
};
const num1 = 100.555.toFixedDown(2)
const num2 = (10.555).toFixedDown(2)
alert(num1+ ' ' + num2);
It is because of precision problem in floating numbers....You can find libraries for precision calculation for npm like
"npm install bigdecimal"
Link here:
BigDecimal Reference
var x = new bigdecimal.BigDecimal("123456.123456789012345678901234567890");
and you can use it like that it should be fine.....
Hope this somewhat clarifies your problem....peace

PHP round($num,2) and javascript toFixed(2) is not giving right output for this value 53.955

I have one php function and having
phpans = round(53.955,2)
and javascript function
var num = 53.955;
var jsans = num.toFixed(2);
console.log(jsans);
both jsans and phpans is giving different $phpans = 53.96 ans jsans = 53.95 . I can not understand why this is happening ..
Thanks is Advance
Because computers can't represent floating numbers properly. It's probably 53.95400000000009 or something like that. The way to deal with this is multiply by 100, round, then divide by 100 so the computer is only dealing with whole numbers.
var start = 53.955,
res1,
res2;
res1 = start.toFixed(2);
res2 = (start * 100).toFixed(0) / 100;
console.log(res1, res2);
//Outputs
"53.95"
53.96
JAvascript toFixed:
The toFixed() method converts a number into a string, keeping a specified number of decimals.
php round:
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
Conclusion tofixed not working like php round. precision Specifies the number of decimal digits to round to.
Javascript function :
function round_up (val, precision) {
power = Math.pow (10, precision);
poweredVal = Math.ceil (val * power);
result = poweredVal / power;
return result;
}

How to remove trailing decimals without rounding up?

For example, I have a number 123.429. How can I remove the trailing decimals without rounding up to two decimal place.
Hence, I need the number to be up to two d.p. i.e 123.42.
Definitely toFixed() method or Math.round(num * 100) / 100 cannot be used in this situation.
The function you want is Math.floor(x) to remove decimals without rounding up (so floor(4.9) = 4).
var number = Math.floor(num * 100) / 100;
Edit: I want to update my answer because actually, this rounds down with negative numbers:
var Math.floor(-1.456 * 100) / 100;
-1.46
However, since Javascript 6, they have introduced the Math.trunc() function which truncates to an int without rounding, as expected. You can use it the same way as my proposed usage of Math.floor():
var number = Math.trunc(num * 100) / 100;
Alternatively, the parseInt() method proposed by awe works as well, although requires a string allocation.
var number = parseInt('' + (num * 100)) / 100;
You can convert it to a string and then simply truncate the string two places after the decimal, e.g.:
var s = String(123.429);
s.substring(0, s.indexOf('.') + 3); // "123.42"
Please note that there's no guarantee if you convert that final string back into a number that it'll be exactly representable to those two decimal places - computer floating point math doesn't work that way.
another v. cool solution is by using | operator
let num = 123.429 | 0
let num = 123.429 | 0
console.log(num);
let's get the variable name as "num"
var num = 123.429;
num=num*100;
num=num.toString();
num=num.split(".");
num=parseInt(num[0]);
num=num/100;
value of the num variable will be 12.42
Try this
number = parseFloat(number).toFixed(12);
number = number.substring(0, number.indexOf('.') + 3);
return parseFloat(number);
Not the fastest solution but the only one that handles an edge case like 0.0006*10000 = 5.999999999 properly, i.e. if you want to truncate to 4 decimal places and the value is exactly 0.0006, then using Math.trunc(0.0006 * (10 ** 4))/(10 ** 4) gives you 0.0005.

Rounding up and rounding down bill amount

I'm facing a problem to get the digit of a number after decimal point. I need the digit to do if else statement.
Here is an example:
31.30 = 31.30
31.31 = 31.30
31.32 = 31.30
31.33 = 31.35
31.34 = 31.35
31.35 = 31.35
31.36 = 31.35
31.37 = 31.35
31.38 = 31.40
31.39 = 31.30
So, I need to get the second digit after decimal point. Then, i can use the digit to do if else statement. This rounding issue is happening in Malaysia.
Something like this might work for doing the rounding to the nearest 5 cents, although then you may need to format the output to have the proper number of digits past the decimal point:
var origVal = 31.34;
var roundedVal = Math.round(origVal*20)/20;
Which would give you 31.35, i.e., rounded to the nearest nickel.
This seems a little more direct than getting the digit and doing an if/else.
Simply try Math.round(x*100%10)
for a part of your question
you can round javascript to specific precision by
Link :Number rounding in JavaScript
var original=28.453
1) //round "original" to two decimals
var result=Math.round(original*100)/100 //returns 28.45
2) // round "original" to 1 decimal
var result=Math.round(original*10)/10 //returns 28.5
3) //round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000 //returns 8.111
from How can I round down a number in Javascript?
Round towards negative infinity - Math.floor()
+3.5 => +3.0
-3.5 => -4.0
Round towards zero - usually called Truncate(), but not supported by JavaScript - can be emulated by using Math.ceil() for negative numbers and Math.floor() for positive numbers.
+3.5 => +3.0 using Math.floor()
-3.5 => -3.0 using Math.ceil()

How do I round a number in JavaScript?

While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of
Name : Value
Name2 : Value2
etc.
The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form 2.20011E+17. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?
If you need to round to a certain number of digits use the following function
function roundNumber(number, digits) {
var multiple = Math.pow(10, digits);
var rndedNum = Math.round(number * multiple) / multiple;
return rndedNum;
}
You hav to convert your input into a number and then round them:
function toInteger(number){
return Math.round( // round to nearest integer
Number(number) // type cast your input
);
};
Or as a one liner:
function toInt(n){ return Math.round(Number(n)); };
Testing with different values:
toInteger(2.5); // 3
toInteger(1000); // 1000
toInteger("12345.12345"); // 12345
toInteger("2.20011E+17"); // 220011000000000000
According to the ECMAScript specification, numbers in JavaScript are represented only by the double-precision 64-bit format IEEE 754. Hence there is not really an integer type in JavaScript.
Regarding the rounding of these numbers, there are a number of ways you can achieve this. The Math object gives us three rounding methods wich we can use:
The Math.round() is most commonly used, it returns the value rounded to the nearest integer. Then there is the Math.floor() wich returns the largest integer less than or equal to a number. Lastly we have the Math.ceil() function that returns the smallest integer greater than or equal to a number.
There is also the toFixed() that returns a string representing the number using fixed-point notation.
Ps.: There is no 2nd argument in the Math.round() method. The toFixed() is not IE specific, its within the ECMAScript specification aswell
Here is a way to be able to use Math.round() with a second argument (number of decimals for rounding):
// 'improve' Math.round() to support a second argument
var _round = Math.round;
Math.round = function(number, decimals /* optional, default 0 */)
{
if (arguments.length == 1)
return _round(number);
var multiplier = Math.pow(10, decimals);
return _round(number * multiplier) / multiplier;
}
// examples
Math.round('123.4567', 2); // => 123.46
Math.round('123.4567'); // => 123
You can also use toFixed(x) or toPrecision(x) where x is the number of digits.
Both these methods are supported in all major browsers
You can use Math.round() for rounding numbers to the nearest integer.
Math.round(532.24) => 532
Also, you can use parseInt() and parseFloat() to cast a variable to a certain type, in this case integer and floating point.
A very good approximation for rounding:
function Rounding (number, precision){
var newNumber;
var sNumber = number.toString();
var increase = precision + sNumber.length - sNumber.indexOf('.') + 1;
if (number < 0)
newNumber = (number - 5 * Math.pow(10,-increase));
else
newNumber = (number + 5 * Math.pow(10,-increase));
var multiple = Math.pow(10,precision);
return Math.round(newNumber * multiple)/multiple;
}
Only in some cases when the length of the decimal part of the number is very long will it be incorrect.
Math.floor(19.5) = 19 should also work.

Categories