Format number to last two decimals - javascript

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)

Related

Can you tell me why my code for turning an array to a number, adding one, and returning an array only works on some datasets?

I'm trying to solve the following Leetcode problem:
You are given a large integer represented as an integer array digits,
where each digits[i] is the ith digit of the integer. The digits are
ordered from most significant to least significant in left-to-right
order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of
digits.
Example 1:
Input: digits = [1,2,3] Output: [1,2,4] Explanation: The array
represents the integer 123. Incrementing by one gives 123 + 1 = 124. Thus, the result should be [1,2,4].
Here's my code :
var plusOne = function(digits) {
let newDigit = digits.join('')
if (newDigit.length > 15) {
let digitLength = newDigit.length
let secondHalf = newDigit.slice(digitLength - 15, digitLength)
secondHalf = parseInt(secondHalf) + 1
secondHalf = Array.from(String(secondHalf), Number)
digits.splice(digitLength - 15, 15)
return digits.concat(secondHalf)
}
let Digit = parseInt(newDigit) + 1
const answer = Array.from(String(Digit), Number)
return answer
};
Works for many data sets. Get's the following error on the following set. Why :(
When you do parseInt(secondHalf), you're effectively dropping any leading zeros in that string, and as a result those zeros don't get included in the final array. The input digits are guaranteed not to have any leading zeros, but that doesn't mean that there won't be any leading zeros if you slice the string in the middle.
Also, even fixing that, what about input arrays that are longer than 30 characters?
Consider using a BigInt instead, it'll be a lot easier.
const plusOne = function(digits) {
const bigInt = BigInt(digits.join('')) + 1n;
return [...String(bigInt)].map(Number);
}
console.log(plusOne(
'590840235570031372488506112'.split('').map(Number)
));

Add fixed 2 decimals to a number using 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......

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

Creating a string of digits in javascript each within a limit

How can I use javascript to randomly create a 20 digit string of numbers, each of the digits ranging only between 1 and 5?
An example would be: 52431425331425141521
As well as the logical algorithm I gave in my comment above, you could just use this one-liner:
var result = Math.floor(Math.random()*95367431640625).toString(5)
.split("").map(function(n) {return +n+1;}).join("");
Essentially, pick a random integer between 0 and 520-1, convert it to base 5, then increment all the digits by one, so they're all between 1 and 5 ^_^
EDIT: Just realised this won't handle low numbers too well. Try this:
var result = (
new Array(20).join("0")
+
Math.floor(Math.random()*95367431640625).toString(5)
).slice(-20).split("").map(function(n) {return +n+1;}).join(""));
This does basically the same, except it prepends 19 zeroes to the front of your number, then slices off the last 20 characters. This will allow it to handle leading zeroes correctly to give a 20-digit number in all cases.
You can use this:
function random_string()
{
var text = "";
var string = "12345";
for( var i=0; i < 20; i++ )
text += string.charAt(Math.floor(Math.random() * string.length));
return text;
}
random_string();

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