Javascript number format to decimal - javascript

I have a question about decimal numbers. I need to convert my numbers to decimal but I couldn't get what I exactly want.
What I want is:
I want to convert 130000 to 130,000 and 20911.56 to 20,911,56 (etc.)
First of all I searched in here and found some solutions to change my numbers :
function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){
var numbers = string.toString().match(/\d+/g).join([]);
numbers = numbers.padStart(decimals+1, "0");
var splitNumbers = numbers.split("").reverse();
var mask = '';
splitNumbers.forEach(function(d,i){
if (i == decimals) { mask = decimal + mask; }
if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; }
mask = d + mask;
});
return pre + mask + pos;
}
var element = document.getElementById("format");
var money= number_format("130000",2,',','.');
element.innerHTML = money;
This code above gave me 20.911,56 but it didn't give me 130,000. Instead it is 1,300,00.What should I do? Can't I have them on the same time?

Just use Intl.NumberFormat as follows:
const formatter = new Intl.NumberFormat('en');
console.log(formatter.format(130000)); // 130,000
console.log(formatter.format(20911.56)); // 20,911.56

Related

From Decimal to Binary system

I want to make an easy website because I want to learn javascript. The website will have just one (number) input named "number". After clicking on submit button the website will convert the number from decimal to binary system and show the answer.
This is the javascript part that should convert the number and show the answer in a div with ID = result:
var selectedNumber = document.getElementByName("number").value;
var k = [];
var a = 0;
var b = 1;
while (selectedNumber > 1){
if(selectedNumber%2 < 1){
k=k.append(a);
selectedNumber = Math.floor(selectedNumber/2);
}
else{
k=k.append(b);
selectedNumber = Math.floor(selectedNumber/2);
}
}
k=k.append(b);
for i in reversed(k){
document.getElementById("result").innerHETML = i;
}
Unfortunately, I don't have much experience using javascript and this code doesn't work. I've made a similar program in python and based this code on that in python.
Here's the corrected code:
Tip - Whenever you have to glue two numbers to form a string make sure to do 1 + "" +2
var selectedNumber = 105;//document.getElementByName("number").value;
var k = [];
var a = 0;
var b = 1;
var output = '';
while (selectedNumber > 1){
if(selectedNumber%2 < 1){
k=k+""+a;
selectedNumber = Math.floor(selectedNumber/2);
}
else{
k=k+""+b;
selectedNumber = Math.floor(selectedNumber/2);
}
}
k=k+""+b;
console.log(k);
//document.getElementByName("number").value = k;
Simplest way is to use toString(2) method.
let a =7
console.log(a.toString(2))
I have made some minor changes to your code. removed redundant lines. i am appending values to a front of string instead of an array ( which you later reverse and join).
function handle(){
let selectedNumber = document.getElementById("number").value;
let k = '',a = 0, b = 1;
while (selectedNumber > 1){
if(selectedNumber%2 < 1){
k= a+k
}
else{
k=b+k
}
selectedNumber = Math.floor(selectedNumber/2);
}
k=b+k;
document.getElementById("result").innerHTML = k;
}
#result{
color: green;
font-size:25px;
}
<input id='number' placeholder='enter value'></input>
<button onClick=handle()>Convert to binary</button>
<div id='result'></div>
It's a whole lot simpler than that. The .toString() method takes an optional argument that can be used to convert a number to a different numerical base system, like its binary, octal or hex values.
Prepending the input's value with +, forces the input's value to become a number.
document.querySelector("button").addEventListener("click", function(){
let number = +document.querySelector("input").value; // Convert input into a string
console.clear();
console.log("The decimal: " + number + " converted to a binary is: " + number.toString(2));
console.log("The decimal: " + number + " converted to an octal is: " + number.toString(8));
console.log("The decimal: " + number + " converted to a hex is: " + number.toString(16));
});
<input><button>Convert!</button>
For this goal, actually you can forget all your code and simple use Number.prototype.toString(). It takes an optional argument of the base you want to use for convert the number to string.
Example:
const convert = () =>
{
let number = document.getElementById("iNumber").value;
binNumber = Number.parseInt(number, 10).toString(2);
document.getElementById("dRes").innerHTML = binNumber;
};
<input id="iNumber" type="number">
<button id="btnToBinary" onclick="convert()">
Convert To Binary
</button>
<div id="dRes"></div>

Automate replace a lot content strings in JavaScript

I have an string with HTML format, and I need to replace ALL the math exponents in HTML format <sup></sup>, to math exponents without HTML format.
I'm using the replace() method, but I need find and replace 100 exponents, from <sup>1</sup> to <sup>100</sup>, and I should write all the numbers (from 1 to 100).
var copiar = texto.
replace(/<br>/g, "\n").
replace(/<sup><\/sup>/g, "").
replace(/<sup>2<\/sup>/g, "²").
replace(/<sup>3<\/sup>/g, "³").
replace(/<sup>4<\/sup>/g, "⁴").
replace(/<sup>5<\/sup>/g, "⁵").
replace(/<sup>6<\/sup>/g, "⁶").
replace(/<sup>7<\/sup>/g, "⁷").
replace(/<sup>8<\/sup>/g, "⁸").
replace(/<sup>9<\/sup>/g, "⁹").
replace(/<sup>10<\/sup>/g, "¹⁰");
...
replace(/<sup>100<\/sup>/g, "¹⁰⁰");
My question is: There is a way to automate this task? Thanks!
UPDATE: I'm doing this replacements because I'm developing an App for iOS, capable to print (in HTML format) and copy to clipboard (plane text). That's the reason because I'm replacement the <sup> numbers.
UPDATE 14/Oct/2014: I was needing to replace negative exponents too. Using the #minitech answer and modifying a little, I could be able to replace ALL the exponents (positive and negative). Maybe can be useful for someone, here the code:
var map = '⁰¹²³⁴⁵⁶⁷⁸⁹';
var copiar = texto.replace(/<sup>(\-*(\d*))<\/sup>/g, function (str, digits){
return Array.prototype.map.call(digits, function (digit) {
var exp = "";
if (digit != '-') {
exp += map.charAt(digit);
} else {
exp += "¯";
}
return exp;
}).join('');
});
A string and charAt provide a convenient way to map digits to the corresponding superscript digits:
var map = '⁰¹²³⁴⁵⁶⁷⁸⁹';
var copiar = texto.replace(/<sup>(\d*)<\/sup>/g, function (_, digits) {
return Array.prototype.map.call(digits, function (digit) {
return map.charAt(+digit);
}).join('');
});
When you do a replacement, you can supply a function to calculate it, instead of a fixed string. So you can use a pattern for all your <sup> replacements, and use a function that translates the number to Unicode superscripts.
var copiar = texto.
replace(/<br>|<sup>(\d*)<\/sup>/g, function(match, digits) {
if (match == "<br>") {
return "\n";
}
// Rest is for translating superscripts to Unicode
var superdigits = '';
var zero = "0".charCodeAt(0);
var superzero = 0x2070;
var supertwo = 0x00b2;
for (var i = 0; i < digits.length; i++) {
var n = digits.charCodeAt(i) - zero;
var char;
switch (n) {
// Superscripts 2 and 3 are at weird places in Unicode
case 2: case 3:
char = String.fromCharCode(n - 2 + supertwo);
break;
default:
char = String.fromCharCode(n + superzero);
}
superdigits += char;
}
return superdigits;
});
<script>
function get_sup_index(num) {
var new_num = new String(num);
new_num = new_num.replace(/0/g, "⁰").
replace(/1/g, "¹").
replace(/2/g, "²").
replace(/3/g, "³").
replace(/4/g, "⁴").
replace(/5/g, "⁵").
replace(/6/g, "⁶").
replace(/7/g, "⁷").
replace(/8/g, "⁸").
replace(/9/g, "⁹");
return new_num;
}
var my_text = '<sup>1</sup>'+
'<sup>2</sup>'+
'<sup>3</sup>'+
'<sup>4</sup>'+
'<sup>5</sup>'+
'<sup>6</sup>'+
'<sup>7</sup>'+
'<sup>8</sup>'+
'<sup>9</sup>'+
'<sup>10</sup>';
alert(get_sup_index(my_text.replace(/<sup>([0-9]*)<\/sup>/g, "\$1")));
</script>
I hope that can help you.

Format amount on keyup

I would like to format amount on keyup javascript event. I need a result like this:
100 > 100
1000 > 1 000
100000000 > 100 000 000
1000,12 > 1 000,12
Can you help me please?
Here's a wacky format function that was fun to think about:
function formatNumber(s) {
var parts = s.split(/,/)
, spaced = parts[0]
.split('').reverse().join('') // Reverse the string.
.match(/\d{1,3}/g).join(' ') // Join groups of 3 digits with spaces.
.split('').reverse().join(''); // Reverse it back.
return spaced + (parts[1] ? ','+parts[1] : ''); // Add the fractional part.
}
You can attach it to an element's "keyup" event by using element.addEventListener(...) in pure JavaScript or the .on(...) function in jQuery, e.g.:
$('.my-input').on('keyup', function() {
var $this = $(this);
$this.val(formatNumber($this.val());
});
You need something like this:
function formatNumber(numberString) {
var commaIndex = numberString.indexOf(',');
var int = numberString;
var frac = '';
if (~commaIndex) {
int = numberString.slice(0, commaIndex);
frac = ',' + numberString.slice(commaIndex + 1);
}
var firstSpanLength = int.length % 3;
var firstSpan = int.slice(0, firstSpanLength);
var result = [];
if (firstSpan) {
result.push(firstSpan);
}
int = int.slice(firstSpanLength);
var restSpans = int.match(/\d{3}/g);
if (restSpans) {
result = result.concat(restSpans);
return result.join(' ') + frac;
}
return firstSpan + frac;
}
formatNumber('1234567890,12'); // "1 234 567 890,12"
Use it with your event listener and send to this function strings that represents numbers and it will return strings int the desired format
input.onkeyup = function () {
input.value = input.value.replace(/\d+(?:,\d+)?/g, formatNumber);
};
function formatNumberField() {
// unformat the value
var value = this.value.replace(/[^\d,]/g, '');
// split value into (leading digits, 3*x digits, decimal part)
// also allows numbers like ',5'; if you don't want that,
// use /^(\d{1,3})((?:\d{3})*))((?:,\d*)?)$/ instead
var matches = /^(?:(\d{1,3})?((?:\d{3})*))((?:,\d*)?)$/.exec(value);
if (!matches) {
// invalid format; deal with it however you want to
// this just stops trying to reformat the value
return;
}
// add a space before every group of three digits
var spaceified = matches[2].replace(/(\d{3})/g, ' $1');
// now splice it all back together
this.value = [matches[1], spaceified, matches[3]].join('');
}
// attaching event handler with jQuery...
$(document).ready(function() {
$('#your-element-id').on('keyup', formatNumberField);
});
// With vanilla JS, it can get a little ugly. This is the simplest way that
// will work in pretty much all browsers.
// Stick this in your "dom is loaded" callback
document.getElementById('your-element-id').onkeyup = formatNumberField;

How to convert a very large hex number to decimal in javascript

I am trying without much success to convert a very large hex number to decimal.
My problem is that using deciaml = parseInt(hex, 16)
gives me errors in the number when I try to convert a hex number above 14 digits.
I have no problem with this in Java, but Javascript does not seem to be accurate above 14 digits of hex.
I have tried "BigNumber" but tis gives me the same erroneous result.
I have trawled the web to the best of my ability and found web sites that will do the conversion but cannot figure out how to do the conversion longhand.
I have tried getting each character in turn and multiplying it by its factor i.e. 123456789abcdef
15 * Math.pow(16, 0) + 14 * Math.pow(16, 1).... etc but I think (being a noob) that my subroutines may not hev been all they should be because I got a completely (and I mean really different!) answer.
If it helps you guys I can post what I have written so far for you to look at but I am hoping someone has simple answer for me.
<script>
function Hex2decimal(hex){
var stringLength = hex.length;
var characterPosition = stringLength;
var character;
var hexChars = new Array();
hexChars[0] = "0";
hexChars[1] = "1";
hexChars[2] = "2";
hexChars[3] = "3";
hexChars[4] = "4";
hexChars[5] = "5";
hexChars[6] = "6";
hexChars[7] = "7";
hexChars[8] = "8";
hexChars[9] = "9";
hexChars[10] = "a";
hexChars[11] = "b";
hexChars[12] = "c";
hexChars[13] = "d";
hexChars[14] = "e";
hexChars[15] = "f";
var index = 0;
var hexChar;
var result;
// document.writeln(hex);
while (characterPosition >= 0)
{
// document.writeln(characterPosition);
character = hex.charAt(characterPosition);
while (index < hexChars.length)
{
// document.writeln(index);
document.writeln("String Character = " + character);
hexChar = hexChars[index];
document.writeln("Hex Character = " + hexChar);
if (hexChar == character)
{
result = hexChar;
document.writeln(result);
}
index++
}
// document.write(character);
characterPosition--;
}
return result;
}
</script>
Thank you.
Paul
The New 'n' Easy Way
var hex = "7FDDDDDDDDDDDDDDDDDDDDDD";
if (hex.length % 2) { hex = '0' + hex; }
var bn = BigInt('0x' + hex);
var d = bn.toString(10);
BigInts are now available in most browsers (except IE).
Earlier in this answer:
BigInts are now available in both node.js and Chrome. Firefox shouldn't be far behind.
If you need to deal with negative numbers, that requires a bit of work:
How to handle Signed JS BigInts
Essentially:
function hexToBn(hex) {
if (hex.length % 2) {
hex = '0' + hex;
}
var highbyte = parseInt(hex.slice(0, 2), 16)
var bn = BigInt('0x' + hex);
if (0x80 & highbyte) {
// You'd think `bn = ~bn;` would work... but it doesn't
// manually perform two's compliment (flip bits, add one)
// (because JS binary operators are incorrect for negatives)
bn = BigInt('0b' + bn.toString(2).split('').map(function (i) {
return '0' === i ? 1 : 0
}).join('')) + BigInt(1);
bn = -bn;
}
return bn;
}
Ok, let's try this:
function h2d(s) {
function add(x, y) {
var c = 0, r = [];
var x = x.split('').map(Number);
var y = y.split('').map(Number);
while(x.length || y.length) {
var s = (x.pop() || 0) + (y.pop() || 0) + c;
r.unshift(s < 10 ? s : s - 10);
c = s < 10 ? 0 : 1;
}
if(c) r.unshift(c);
return r.join('');
}
var dec = '0';
s.split('').forEach(function(chr) {
var n = parseInt(chr, 16);
for(var t = 8; t; t >>= 1) {
dec = add(dec, dec);
if(n & t) dec = add(dec, '1');
}
});
return dec;
}
Test:
t = 'dfae267ab6e87c62b10b476e0d70b06f8378802d21f34e7'
console.log(h2d(t))
prints
342789023478234789127089427304981273408912349586345899239
which is correct (feel free to verify).
Notice that "0x" + "ff" will be considered as 255, so convert your hex value to a string and add "0x" ahead.
function Hex2decimal(hex)
{
return ("0x" + hex) / 1;
}
If you are using the '0x' notation for your Hex String, don't forget to add s = s.slice(2) to remove the '0x' prefix.
Keep in mind that JavaScript only has a single numeric type (double), and does not provide any separate integer types. So it may not be possible for it to store exact representations of your numbers.
In order to get exact results you need to use a library for arbitrary-precision integers, such as BigInt.js. For example, the code:
var x = str2bigInt("5061756c205768697465",16,1,1);
var s = bigInt2str(x, 10);
$('#output').text(s);
Correctly converts 0x5061756c205768697465 to the expected result of 379587113978081151906917.
Here is a jsfiddle if you would like to experiment with the code listed above.
The BigInt constructor can take a hex string as argument:
/** #param hex = "a83b01cd..." */
function Hex2decimal(hex) {
return BigInt("0x" + hex).toString(10);
}
Usage:
Hex2decimal("100");
Output:
256
A rip-off from the other answer, but without the meaningless 0 padding =P

Add a decimal to a string

I have a script that takes a big number and counts up. The script converts the number to a string so that it can be formatted with commas, but I also need to add a decimal place before the last two digits. I know that this line handles the commas:
if ((i+1) % 3 == 0 && (amount.length-1) !== i)output = ',' + output;
Is there a similar line of code I can add that accomplishes adding a decimal point?
Yes, if you always want the decimal before the last two:
function numberIt(str) {
//number before the decimal point
num = str.substring(0,str.length-3);
//number after the decimal point
dec = str.substring(str.length-2,str.length-1)
//connect both parts while comma-ing the first half
output = commaFunc(num) + "." + dec;
return output;
}
When commaFunc() is the function you described that adds commas.
EDIT
After much hard work, the full correct code:
http://jsfiddle.net/nayish/TT8BH/21/
Are you sure want the decimal to be just before the last two digits? That way 1234 would become 12.34 and not 1234.00, I'm assuming you want the second one, in that case you should use JavaScript's built in method .toFixed()
Note I didn't write the format_number function, I took it from the website below and modified it a bit.
http://www.mredkj.com/javascript/nfbasic2.html
http://www.mredkj.com/javascript/nfbasic.html
// example 1
var num = 10;
var output = num.toFixed(2); // output = 10.00
// example 2, if you want commas aswell
function format_number(nStr)
{
nStr = nStr.toFixed(2);
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
var num = 1234;
var output = format_number(num); // output = 1,234.00

Categories

Resources