How do I convert an integer to decimal in JavaScript? - javascript

I have a number in JavaScript that I'd like to convert to a money format:
556633 -> £5566.33
How do I do this in JavaScript?

Try this:
var num = 10;
var result = num.toFixed(2); // result will equal string "10.00"

This works:
var currencyString = "£" + (amount/100).toFixed(2);

Try
"£"+556633/100

This script making only integer to decimal.
Seperate the thousands
onclick='alert(MakeDecimal(123456789));'
function MakeDecimal(Number) {
Number = Number + "" // Convert Number to string if not
Number = Number.split('').reverse().join(''); //Reverse string
var Result = "";
for (i = 0; i <= Number.length; i += 3) {
Result = Result + Number.substring(i, i + 3) + ".";
}
Result = Result.split('').reverse().join(''); //Reverse again
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
return Result;
}

Using template literals you can achieve this:
const num = 556633;
const formattedNum = `${num/100}.00`;
console.log(formattedNum);

Related

How to reverse value in javascript

hello I have values like this
1-10
2-3
901-321
I want to get the reverse values for example like this
10-1
3-2
321-901
I have tried this
var str = "1-18";
var newString = "";
for (var i = str.length - 1; i >= 0; i--) {
newString += str[i];
}
return newString;
But it gives me 81-1
Instead, use String.split(), Arrary.reverse() and Arrary.join():
var str = '901-321';
var strArray = str.split('-'); // ['901', '321']
var strArrayReversed = strArray.reverse(); // ['321', '901']
var result = strArrayReversed.join('-'); // '321-901'
console.log('result = ', result);
// You can do all these steps above in one go as:
var result2 = str.split('-')
.reverse()
.join('-');
console.log('result2 = ', result2);
MDN Docs:
String.prototype.split()
Array.prototype.reverse()
Array.prototype.join()
Can split on the - to create array , reverse the array and join it back into string
var str = "1-18",
newStr = str.split('-').reverse().join('-');
console.log(newStr)
a = "12-5"
console.log(a.split('-').reverse().join('-'))
You can use the split method to divide the string in two, and then use the second part before the first, like this:
var str = "1-18";
var l = str.split("-");
return l[1] + "-" + l[0];
You could replace the string by swapping the values.
var string = '901-321';
console.log(string.replace(/(.+)-(.+)/, '$2-$1'));

Index of each CharAt and multiplying each index number

I am trying to multiply each every index number together and seems like parseInt also return a decimal in the end...Not sure why?
var decNum = "12312312312312";
if( decNum.length == 14)
{
var lastnum = decNum.charAt(13);
var newNum = parseInt(decNum)/14; // rather 1231231231231 it shows 1231231231231.2 should be 13 nums left without last digit in int.
var validNum = [1,7,4,2,8,7,3,2,1,2,3,4,1,3];
var sum;
for (var i = 0; i < validNum.length; i++) {
//since I can't use charAt for for INT so parse to string and parse it back to int to do the math.
sum += parseInt(validNum[i]) * parseInt(String(newNum.charAt(i)));
}
parseInt returns a number, so var newNum = parseInt(decNum)/14; results in newNum being a number, not a string. So, you can't use charAt on a number - you want the string. You have decimals because when you divide an integer (decNum) by 14, the result is a continuing decimal.
If you want to use explicit type conversions:
const newNum = String(parseInt(decNum / 14));
You don't need to parseInt the elements of validNum since they're already integers.
Your sum is not initialized to 0, so subsequent sum += lines will fail.
Even after fixing that, it would still be more elegant to use array methods to iterate over the string, though:
const decNum = "12312312312312";
if( decNum.length == 14) {
const newNum = String(parseInt(decNum / 14));
const validNum = [1,7,4,2,8,7,3,2,1,2,3,4,1,3];
const charCodeArr = newNum.split('').map(char => char.charAt(0));
const sum = charCodeArr.reduce((sumSoFar, charCode, i) => {
return sumSoFar + (charCode * validNum[i]);
}, 0);
console.log(sum);
}
everything works fine now, thanks, everyone.
var decNum = "12312312312312";
if( decNum.length == 14)
{
var lastnum = decNum.charAt(13);
var newNum = String(parseInt(decNum)/14);
var validNum = [1,7,4,2,8,7,3,2,1,2,3,4,1,3];
var sum = 0;
for (var i = 0; i < validNum.length; i++) {
sum += parseInt(validNum[i]) * parseInt(newNum.charAt(i));
}

how to get formatted integer value in javascript

This is my integer value
12232445
and i need to get like this.
12,232,445
Using prototype how to get this?
var number = 12232445,
value = number.toString(),
parts = new Array;
while (value.length) {
parts.unshift(value.substr(-3));
value = value.substr(0, value.length - 3);
}
number = parts.join(',');
alert(number); // 12,232,445
It might not be the cleanest solution, but it'll do:
function addCommas(n)
{
var str = String(n);
var result = '';
for(var i = 0; i < str.length; i++)
{
if((i - str.length) % 3 == 0)
result += ',';
result += str[i];
}
return result;
}
Here is the function I use, to format thousands separators and takes into account decimals if any:
function thousands(s) {
var rx = /(-?\d+)(\d{3})/,
intDec = (''+s)
.replace(new RegExp('\\' + $b.localisation.thousandSeparator,'g'), '')
.split('\\' + $b.user.localisation.decimalFormat),
intPart = intDec[0],
decPart = intDec[1] || '';
while (rx.test(intPart)) {
intPart = intPart.replace(rx,'$1'+$b.localisation.thousandSeparator+'$2');
}
return intPart + (decPart && $b.localisation.decimalFormat) + decPart;
}
thousands(1234.56) //--> 1,234.56
$b.localisation is a global variable used for the session.
$b.localisation.thousands can have the values , or . or a space.
And $b.localisation.decimalFormat can have the values , or . depending on the locale of the user

Adding commas, decimal to number output javascript

I'm using the following code to count up from a starting number. What I need is to insert commas in the appropriate places (thousands) and put a decimal point in front of the last two digits.
function createCounter(elementId,start,end,totalTime,callback)
{
var jTarget=jQuery("#"+elementId);
var interval=totalTime/(end-start);
var intervalId;
var current=start;
var f=function(){
jTarget.text(current);
if(current==end)
{
clearInterval(intervalId);
if(callback)
{
callback();
}
}
++current;
}
intervalId=setInterval(f,interval);
f();
}
jQuery(document).ready(function(){
createCounter("counter",12714086+'',9999999999,10000000000000,function(){
alert("finished")
})
})
Executed here: http://jsfiddle.net/blackessej/TT8BH/3/
var s = 121221;
Use the function insertDecimalPoints(s.toFixed(2));
and you get 1,212.21
function insertDecimalPoints(s) {
var l = s.length;
var res = ""+s[0];
console.log(res);
for (var i=1;i<l-1;i++)
{
if ((l-i)%3==0)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res = res.replace(',.','.');
return res;
}
Check out this page for explanations on slice(), split(), and substring(), as well as other String Object functions.
var num = 3874923.12 + ''; //converts to a string
numArray = num.split('.'); //numArray[0] = 3874923 | numArray[1] = 12;
commaNumber = '';
i = numArray[0].length;
do
{
//we don't want to start slicing from a negative number. The following line sets sliceStart to 0 if i < 0. Otherwise, sliceStart = i
sliceStart = (i-3 >= 0) ? i-3 : 0;
//we're slicing from the right side of numArray[0] because i = the length of the numArray[0] string.
var setOf3 = numArray[0].slice(sliceStart, i);
commaNumber = setOf3 + ',' + commaNumber; //prepend the new setOf3 in front, along with that comma you want
i -= 3; //decrement i by 3 so that the next iteration of the loop slices the next set of 3 numbers
}
while(i >= 0)
//result at this point: 3,874,923,
//remove the trailing comma
commaNumber = commaNumber.substring(0,commaNumber.length-1);
//add the decimal to the end
commaNumber += '.' + numArray[1];
//voila!
This function can be used for if not working locale somite
number =1000.234;
number=insertDecimalPoints(number.toFixed(3));
function insertDecimalPoints(s) {
console.log(s);
var temaparray = s.split(".");
s = temaparray[0];
var l = s.length;
var res = ""//+s[0];
console.log(res);
for (var i=0;i<l-1;i++)
{
if ((l-i)%3==0 && l>3)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res =res +"."+temaparray[1];
return res;
}
function convertDollar(number) {
var num =parseFloat(number);
var n = num.toFixed(2);
var q =Math.floor(num);
var z=parseFloat((num).toFixed(2)).toLocaleString();
var p=(parseFloat(n)-parseFloat(q)).toFixed(2).toString().replace("0.", ".");
return z+p;
}

How to convert from Hex to ASCII in JavaScript?

How to convert from Hex string to ASCII string in JavaScript?
Ex:
32343630 it will be 2460
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
hex2a('32343630'); // returns '2460'
Another way to do it (if you use Node.js):
var input = '32343630';
const output = Buffer.from(input, 'hex');
log(input + " -> " + output); // Result: 32343630 -> 2460
For completeness sake the reverse function:
function a2hex(str) {
var arr = [];
for (var i = 0, l = str.length; i < l; i ++) {
var hex = Number(str.charCodeAt(i)).toString(16);
arr.push(hex);
}
return arr.join('');
}
a2hex('2460'); //returns 32343630
You can use this..
var asciiVal = "32343630".match(/.{1,2}/g).map(function(v){
return String.fromCharCode(parseInt(v, 16));
}).join('');
document.write(asciiVal);
** for Hexa to String**
let input = '32343630';
Note : let output = new Buffer(input, 'hex'); // this is deprecated
let buf = Buffer.from(input, "hex");
let data = buf.toString("utf8");
I found a useful function present in web3 library.
var hexString = "0x1231ac"
string strValue = web3.toAscii(hexString)
Update: Newer version of web3 has this function in utils
The functions now resides in utils:
var hexString = "0x1231ac"
string strValue = web3.utils.hexToAscii(hexString)
I've found that the above solution will not work if you have to deal with control characters like 02 (STX) or 03 (ETX), anything under 10 will be read as a single digit and throw off everything after. I ran into this problem trying to parse through serial communications. So, I first took the hex string received and put it in a buffer object then converted the hex string into an array of the strings like so:
buf = Buffer.from(data, 'hex');
l = Buffer.byteLength(buf,'hex');
for (i=0; i<l; i++){
char = buf.toString('hex', i, i+1);
msgArray.push(char);
}
Then .join it
message = msgArray.join('');
then I created a hexToAscii function just like in #Delan Azabani's answer above...
function hexToAscii(str){
hexString = str;
strOut = '';
for (x = 0; x < hexString.length; x += 2) {
strOut += String.fromCharCode(parseInt(hexString.substr(x, 2), 16));
}
return strOut;
}
then called the hexToAscii function on 'message'
message = hexToAscii(message);
This approach also allowed me to iterate through the array and slice into the different parts of the transmission using the control characters so I could then deal with only the part of the data I wanted.
Hope this helps someone else!
console.log(
"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")
)
An optimized version of the implementation of the reverse function proposed by #michieljoris (according to the comments of #Beterraba and #Mala):
function a2hex(str) {
var hex = '';
for (var i = 0, l = str.length; i < l; i++) {
var hexx = Number(str.charCodeAt(i)).toString(16);
hex += (hexx.length > 1 && hexx || '0' + hexx);
}
return hex;
}
alert(a2hex('2460')); // display 32343630
I use this one, it seems more clear to me as I also receive data with spaces like '30 31 38 30 38 30' and the output is 018080
hexToString(hex: string): string {
return hex.split(' ').map(s => string.fromCharCode(parseInt(s,16))).join('');
}

Categories