Add fixed 2 decimals to a number using javascript - javascript

I want to have 2 decimals in a number.
I tried using :
var number = (123).toFixed(2);
but it returns it in a string format. I want them to be numbers.
Also I tried using:
var number= parseFloat((123).toFixed(2));
but this removes the decimals if it is 0.
I want to show the numbers as decimals with fixed 2 decimals, also convert those numbers to toLocaleString("bn-IN-u-nu-latn")
For example:
number = 123456
output : 1,23,456.00

That's impossible. A number won't display trailing zeros past the decimal point. Only a string will.
For example, observe this output:
document.write(0.00); // output as a number, is 0
document.write("<br>");
document.write("0.00"); // output as a string, is 0.00
If you want a number to be rounded to two decimal places, but also have trailing zeros when needed, you must convert to a string before you output, which means (123).toFixed(2) is all you need.
Edit: To round the number, but also use a locale format. Use .toLocaleString() like such:
(0.00).toLocaleString("bn-IN-u-nu-latn", {
minimumFractionDigits:2,
maximumFractionDigits:2
});

Try :
var number = +parseFloat(Math.round(123 * 100) / 100).toFixed(2);

You can try this ..
Html
Value: <input type="text" id="myText" value="">
Javascript
<script>
num = 125;
num=num+1;
var R = num.toFixed(2); // returns 126.00
document.getElementById("myText").value = R;
</script>
Please see below screen......

Related

Format number to last two decimals

I am trying to format numbers in JS to last two decimal.
For example 10100 becomes 101.00 - 606000 becomes 6,060.00 - 7600 becomes 76.00 and so on.
I have tried num.toFixed(2) but that was not of help. I also tried Number(10100).toLocaleString("es-ES", {minimumFractionDigits: 0}) but I end up with 10.100 so it seems off by one decimal.
So
num.toFixed(2)
What its doing its formatting,
Which would be 10.123 -> 10.12
what you should do is divide number by 100.
var number = 10100
number = number / 100
would be what you need.
I will approach this problem by using the help of strings.
Strings can be easily manipulated based on our requirements and then can be converted back to numbers. So, the solution goes like this
Convert the number to string
Manipulate the string to add a decimal before last two character
Convert the string back to number
const formatNumberToLastTwoDecimal = (number) => {
// Convert the number to String
const inputNumAsStr = number.toString();
// Manipulate the string and add decimal before two char
const updatedStr = `${inputNumAsStr.slice(0, -2)}.${inputNumAsStr.slice(-2)}`;
// Return by converting the string to number again
// Fix by 2 to stop parseFloat() from stripping zeroes to right of decimal
return new Number(parseFloat(updatedStr)).toFixed(2);
}
console.log(formatNumberToLastTwoDecimal(606000));
The most simplified way:
output = (number/100).toFixed(2)
And the complex way:
var c = 7383884
a = c.toString()
var output = parseFloat([a.slice(0, -2), ".",a.slice(-2)].join(''))
document.write(output)

How to get a double random number and put its digits to variables?

I want to get a random double number (for example 4.58)
and put its digits to three variables - 4 to the first variable, 5 to the second variable and 8 to the third variable.
Not sure why you need this to be a floating-point number. Just create a three-digit number, convert it to a string, and split it into an array.
var numArr = (Math.floor(Math.random() * 900) + 100).toString().split('');
You can get at the numbers using the normal array method: numArr[0] etc.
To convert it to number, add a period in the first array position and then join it back to together:
numArr.splice(1, 0, '.');
var number = numArr.join('');
DEMO
Alternatively, see this SO question on how to create random floating-point numbers.
You could do something like this:
var number = 4.26; // Your generated double number
output = []; // Array to store each digit
sNumber = number.toString(); // Convert the double to a string so we can split it
for (var i = 0, len = sNumber.length; i < len; i += 1)
{
output.push(+sNumber.charAt(i));
}
console.log(output);
The output will be:
4, 2, 6
All numbers in JavaScript are doubles: that is, they are stored as 64-bit IEEE-754 doubles.
That is, the goal is not to get a "double": the goal is to get the string reprsentation of a number formatted as "YYY.XX". For that, consider Number.toFixed, for instance:
(100).toFixed(2)
The result is the string (not a "double"!) "100.00". The parenthesis are required to avoid a grammar ambiguity in this case (it could also have been written as 100.0.toFixed or 100..toFixed), but would not be required if 100 was in a variable.
Use this. I use .replace(/[.]/g,"") for removing ".".
http://jsfiddle.net/sherali/coyv3erf/2/
var randomNumber = Math.floor(Math.random() * 900) + 100;
numArr= randomNumber.toString().replace(/[.]/g,"").split("")
var number = numArr.join("");
console.log(numArr, number); // ["8", "4", "5"] 845

Tapering/Rounding decimal answers JS calculations

Using JS to run a simple formula, but like many JS calculations I've made before the decimal answers go on for way longer than I'd like and make it look sloppy.
Is there I way I can force the calculation to stop at a certain decimal place or force a round up from there?
Thanks!
<script>
var $u = $('input[name=u]');
var $a = $('input[name=a]');
var $h = $('input[name=h]');
$u.on('keyup',function() {
var u = +$u.val();
var a = +$a.val();
$h.val(u*4.605+a*1.308+28.003).toFixed(1);
});
$a.on('keyup',function() {
var u = +$u.val();
var a = +$a.val();
$h.val(u*4.605+a*1.308+28.003).toFixed(1);
});
</script>
I see you've tried toFixed(). I believe that is the solution, but you're trying to call it on a jQuery object. You should call it on the number before passing it into val().
Change your code to:
$a.on('keyup',function() {
var u = +$u.val();
var a = +$a.val();
$h.val((u*4.605+a*1.308+28.003).toFixed(1));
});
// $('#a').val(Math.PI).toFixed(1); // You're inserting the full value, and then executing
// toFixed on a jQuery Object. Not going to work.
$('#a').val( (Math.PI).toFixed(1) ); // How it should be written
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input id="a"/>
Math.floor(number)
Returns the next integer below given number.
Math.floor(1.66); // 1
Math.floor(-1.66); // -2
Math.ceil(number)
Returns the next integer above given number.
Math.ceil(1.66); // 2
Math.ceil(-1.66); // -1
Math.round(number)
Returns the nearest integer. Similar to Math.floor(number + 0.5);
Math.round(1.66); // 2
Math.round(-1.66); // -2
number|0 (or ~~number)
Discards the decimal portion of a number.
1.66|0; // 1
-1.66|0; // -1
number.toFixed(decimals)
Converts a number into a string with the specified number of decimals. Will either pad the result with zeroes or mathematically round to a certain number of decimals.
(1.66).toFixed(1); // "1.7"
(-1.66).toFixed(1); // "-1.7"
number.toFixed(decimals + 1).slice(0, -1)
Returns a fixed-decimal string, but chops the specified number of decimals without rounding.
(1.66).toFixed(2).slice(0, -1); // "1.6"

How to format numbers in javascript to two decimal digits?

I need to format numbers to two decimal digits in javascript. In order to do this I am using toFixed method which is working properly.
But in cases, where numbers don't have any decimal digits, it should not show decimal point
e.g. 10.00 should be 10 only and not 10.00.
.toFixed() converts the result to String,
so you need to convert it back to Number:
parseFloat( num.toFixed(2) )
or by simply using the Unary +
+num.toFixed(2)
both will give the following:
// 15.00 ---> 15
// 15.20 ---> 15.2
If you only want to get rid of the .00 case, than you can go for String manipulation using .replace()
num.toFixed(2).replace('.00', '');
Note: the above will convert your Number to String.
As an alternative to make this change global(if you need, of course), try this:
var num1 = 10.1;
var num2 = 10;
var tofixed = Number.prototype.toFixed;
Number.prototype.toFixed = function(precision)
{
var num = this.valueOf();
if (num % 1 === 0)
{
num = Number(num + ".0");
}
return tofixed.call(num, precision);
}
console.log(num1.toFixed(2));
console.log(num2.toFixed(2));
Fiddle. This is a mix of this and this post.

How do I select the nth digit in a large integer inside javascript?

When I want to select the nth character, I use the charAt() method, but what's the equivalent I can use when dealing with integers instead of string values?
Use String():
var number = 132943154134;
// convert number to a string, then extract the first digit
var one = String(number).charAt(0);
// convert the first digit back to an integer
var one_as_number = Number(one);
It's a stupid solution but seems to work without converting to string.
var number = 123456789;
var pos = 4;
var digit = ~~(number/Math.pow(10,pos))- ~~(number/Math.pow(10,pos+1))*10;
You could convert the number to a string and do the same thing:
parseInt((number + '').charAt(0))
If you want an existing method, convert it to a string and use charAt.
If you want a method that avoids converting it to a string, you could play games with dividing it by 10 repeatedly to strip off enough digits from the right -- say for 123456789, if you want the 3rd-from-right digit (6), divide by 10 3 times yielding 123456, then take the result mod 10 yielding 6. If you want to start counting digits from the left, which you probably do, then you need to know how many digits (base 10) are in the entire number, which you could deduce from the log base 10 of the number... All this is unlikely to be any more efficient than just converting it to a string.
function digitAt(val, index) {
return Math.floor(
(
val / Math.pow(10, Math.floor(Math.log(Math.abs(val)) / Math.LN10)-index)
)
% 10
);
};
digitAt(123456789, 0) // => 1
digitAt(123456789, 3) // => 4
A bit messy.
Math.floor(Math.log(Math.abs(val)) / Math.LN10)
Calculates the number of digits (-1) in the number.
var num = 123456;
var secondChar = num.toString()[1]; //get the second character
var number = 123456789
function return_digit(n){
r = number.toString().split('')[n-1]*1;
return r;
}
return_digit(3); /* returns 3 */
return_digit(6); /* returns 6 */

Categories