Convert HEX to 4 digit integer - javascript

I am trying to convert a HEX string to 4 digit integer. I can change by the following command but I do not want to generate random integer value every time if same HEX string is passing. The integer number must be same. This is not happening in my case:
const reqq = crypto.createHash('md5').update(admin.companyName).digest('hex');
let valueNum = parseInt(reqq, 16);
let resultValue = Math.floor(Math.random(valueNum) * 9000);
admin.companyID = resultValue;
console.log(resultValue);
How can I make this work ?

Your code to convert the hex hash to a decimal number is correct. If you do not want a different companyName to lead to a different hash, you can remove the random call in resultValue. You can verify your hex conversion is correct by using a converter

Related

Not able to Change String (innerHtml) to Number with Javascript

I am not able to change string from innerHTML to number with javascript, the innerHTML of the element is like 1.2.34, I have tried ParseFloat, ParseInt and Number functions, they are working but only for the string(innerHTML) which is in the form of 1.23 means having only one decimal point, but in my case I have more than 1, 2 decimals and not able to change them in js. PLEASE help me fix this problem.
parseFloat, parseInt can be applied only for the text or number having proper decimal format. ex : 100,1.24,100.24,100.254 but you are trying with 1.2.4 which is not a valid decimal formats, when you try to parse this invalid format with int or float, the JS will consider as invalid arguments for the parseInt or parseFloat.
So i am considering the innerHtml as hh.mm.ss paster the code snippet as below
var time = '1.24.3'; // input string from innerHtml
var timearray = time.split('.'); // split it with .
// You can multiply hours to seconds or minutes
var totalminutes = (+timearray[0]) * 60 + (+timearray[1]);
//then you can add the every time and divide by n
-->You logic goes here

parseInt fixing the value

Here I have a value with commas.
Ex:-var abc = "10,10.12";
If I use var x = parseInt(abc);
it is returning 10
Expected output is 10,10.12
as I have used ng-value="UpdatedPropuesta.VALOR_CUOTA | number:2" in JSP.
If you want an array of numbers out of the string then try this,
const input = "10,10.12";
var output = input.split(",");
output = output.map(i => Number(i));
console.log(output);
10,10.12
That is not the number 1010.12, it is the number 10, a comma operator, and the number 10.12.
Commas are not part of the JavaScript literal syntax.
However, in your case you're passing two arguments to parseInt, the first should be a string to convert (but JS will convert it to a strign) and the second is the radix – the number base – which should be an integer.
So JS's type conversion will lead to:
var x = parseInt('10', 10);
Which is of course 10.
After question update
var x = parseInt("10,10.12");
As comma are not part of JS numeric literals, the parse will stop at the comma because it is not a character that can appear in a number.
So the answer is still 10.

Display "$xx.90" instead of "$xx.9" in Javascript

When I use p=10000 ,r=15 and n=60 in the below ...
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100).toFixed(2));
x = 237.9 instead of 237.90.
If the combo of p, r and n result in a number that is not $xx.x", then the code snippet works fine ...ie. formats to 2 decimal places.
But why is it displaying 237.9 instead of 237.90?
When you call number.toFixed(2), you do indeed get a string representation of the number with two decimal digits:
var number = 237.9;
number.toFixed(2); // '237.90'
However, when you then use parseFloat on this, you convert it back to a number again; since a number does not contain information about the number of zeros to display, the last zero is dropped as it is printed:
parseFloat(number.toFixed(2)); // 237.9
To avoid this, simply don't convert your string back into a float, but use it as a string.
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
p=10000,r=15, n=60;
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
console.log(x)
Add toFixed after all operations. You need string, basically...

Javascript: using toLocaleString + Tofixed

I need to format a number for a project im working on at work, only problem is that I cant format it how i want.
I convert the number to a localestring using the toLocaleString method which gives me the commas but i also need decimal places, nothing i seem to do works.
var number = 123.322
number = parseFloat(number).toFixed(2) //123.22
number.toLocaleString() //123.22
The above code just returns the parsefloated number along with the tofixed decimal values but it doesn't add the commas.
How do i get a number to have two decimal places (when the value is 'xx.00') and also be comma separated. Is this possible in JavaScript?
You can give an object to .toLocaleString() which describes what you want:
var sNumber = (10123.322).toLocaleString(undefined,
{'minimumFractionDigits':2,'maximumFractionDigits':2});
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
Original:
const fNumber = 10123.322;
const sNumber = parseFloat(fNumber.toFixed(2)).toLocaleString();
console.log(sNumber);
The number is already in decimal/float format on the first line.
.toFixed(2) turns it into a string using fixed-point notation.
parseFloat() takes that string and turns it back into a float.
.toLocaleString() turns it into a string using the local format.
Just to do it in one line
var num = '12233.3366554';
num = parseFloat(parseFloat(num).toFixed(2)).toLocaleString('en-IN', { useGrouping: true });
Yes, it is possible using .toLocaleString, yo just need to specify the language, optionally you can specify decimals and currency. look at this example:
35000.2455.toLocaleString('en-IN', {minimumFractionDigits: 2, maximumFractionDigits: 2,style: 'currency', currency: 'USD' })
this returns $35,000.25
Number.toLocaleString works on a number, but toFixed returns a string.
Coerce the string back into a number first
var number = 123.322;
var string = parseFloat(number).toFixed(2);
var parsed = (+string).toLocaleString();
console.log(parsed);
In order to get commas you have to specify the locale .The locale en includes commas for the numbers. toFixed() Returns a string. toLocaleString() function commas works on a number not on a string.So parse the string to float.
var number = 1234567.322;
number = parseFloat(parseFloat(number).toFixed(2)).toFixed(2) ;
number=number.toLocaleString('en');
toLocaleString function provide number representation based on languages
var number = 3500.00;
if(Number.isInteger(number)){
var zeroappend= number.toLocaleString()+".00";
console.log(zeroappend);//3,500.00;
}else{
console.log(number.toLocaleString());
}

Getting a random background color in javascript

I am new to java-script . I need to get a random background color whenever i call a particular function.
I found the following code on the web but i don't quite understand how it works.
Code:
function getRandomColor () {
var hex = Math.floor(Math.random() * 0xFFFFFF);
return "#" + ("000000" + hex.toString(16)).substr(-6);
}
How is the above code working.I understand how Math.random() works but what does hex.toString(16)).substr(-6) basically signify?
Can some one please clarify it to me how the above code works.
function getRandomColor () {
var hex = Math.floor(Math.random() * 0xFFFFFF);
return "#" + ("000000" + hex.toString(16)).substr(-6);
}
hex.toString(16) converts hex into string number representation in base 16.
Syntax:
number.toString(radix)
radix: Base to use for representing a numeric value. Must be an integer between 2 and 36.
2 - The number will show as a binary value
8 - The number will show as an octal value
16 - The number will show as an hexadecimal value
substr(-6) just takes the last 6 characters, which cuts off the "000000" because they're not part of the last 6 characters.
hex.toString(16) converts hex into string number representation in base 16. Then it appends 000000 at the beginning of the string to make sure it will be at least of length 6. and substr(-6) takes last 6 chars of the resulting string. This way you always get # + 6 hex chars. Which represents color.
The code first picks a random number and using the "& 0xFFFFFF" technique it ensures the range is something like 0 to 16777215.
Once we have that random number we convert to hexadecimal using the ".toString(16)" method, the 16 signifying we want hexadecimal conversion.
Now, we can think we have a 6 digit random number in hex to use for our color but know that the ".toString(16)" method does not do any padding for us.
For example, if the random number is 255 which is FF in hex, is not usable as it since it is not precisely 6 digits long.
One technique is to do a string length check and add the corresponding number of 0's to the beginning of the 'FF' to get '0000FF'.
Here we see another technique where you see a fixed number of 0's added to the string and then a fixed length is chopped of the end, ensuring you get 6 digits and correctly padded.
I've always used the string length check or specific padding functions (I don't know if javascript has one) - I only answered the question so as to fully appreciate the technique shown in this question.
/* a complete html page to apply this */
<html>
<body>
<button type="button" onclick="setbodybgcolor()">Random Background</button>
<script>
function setbodybgcolor(){
document.body.style.backgroundColor=getRandomColor ();
}
function getRandomColor () {
var hex = Math.floor(Math.random() * 0xFFFFFF);
return "#" + (hex.toString(16)).substr(-6);
}
/* we can do this also
function setbodybgcolor(){
var hex=Math.floor(Math.random()*16777215).toString(16);
document.body.style.backgroundColor="#"+hex;
}*/
</script>
</body>
</html>

Categories

Resources