Javascript get decimal and thousands separator from NumberFormat - javascript

I'm looking for a method to get decimal and thousands separators from NumberFormat object.
var de = new Intl.NumberFormat('de-DE');
Later I plan to use them to parse formated string back to Javascript's float. I know I could create sample number and then scan it with regex but I feel there must be some easier method to get those separators.

Seems you can avoid doing the parsing yourself:
Intl.NumberFormat('de-CH').v8Parse(
Intl.NumberFormat('de-CH').format(1000) // => 1'000
) // => 1000
But this sounds very chrome-specific :)
But if I were you I'd avoid parsing localized numbers represented as strings to numbers if I can.

Here the js function which will return formatted
function customNumberFormat( num){
var parts = (''+ (num<0?-num:num)).split("."), s=parts[0], i=L= s.length, o='',c;
while(i--){ o = (i==0?'':((L-i)%3?'':','))+s.charAt(i) +o }
return (num<0?'-':'') + o + (parts[1] ? '.' + parts[1] : '');
}

Related

javascript toFixed not working in my calculations

Hi guys I have bytes say 007458415820874584158208042423283712.I want to convert this into GB, so tried to divide it by 1048576 i am getting a result of 7.112899609446129e+27. I want only the two numbers after the decimal point, so I have used .toFixed like below. It doesn't work, I am getting the same response as if I have not used the toFixed function. I just want the result to be just 7.1. help me out on this.
console.log((007458415820874584158208042423283712/1048576).toFixed(2));
You can use this prototype function for your solution.
Number.prototype.toFixedSpecial = function(n) {
var str = this.toFixed(n);
if (str.indexOf('e+') === -1)
return str;
// if number is in scientific notation, pick (b)ase and (p)ower
str = str.replace('.', '').split('e+').reduce(function(p, b) {
return p + Array(b - p.length + 2).join(0);
});
if (n > 0)
str += '.' + Array(n + 1).join(0);
return str;
};
var val = (007458415820874584158208042423283712/1048576);
console.log(val);
console.log(val.toFixedSpecial(2)) //"7112899609446129000000000000.00"
console.log( 1e21.toFixedSpecial(2) ); // "1000000000000000000000.00"
console.log( 2.1e24.toFixedSpecial(0) ); // "2100000000000000000000000"
console.log( 1234567..toFixedSpecial(1) ); // "1234567.0"
console.log( 1234567.89.toFixedSpecial(3) ); // "1234567.890"
Your problem is that this is scientific notation and toFixed() supports 20 decimal places. Your number is 7.112899609446129e+27 which technically (most likely) has decimal places but they are not visible due to scientific notation.
The solution would be to use toExponential() like so:
parseFloat((7458415820874584158208042423283712/1048576.0).toExponential(2))
Output:
7.11e+27
A more correct way is shown here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential
But this gives "7.11e+27" (a string)
If you just want 7.11 then you can use slice(0,3) as follows:
var result_str = (7458415820874584158208042423283712/1048576).toExponential(2);
console.log(parseFloat(result_str.slice(0,3)));
Result: 7.1

Regarding decimal in javascript

When i am writing 11.00 it is displaying 11.00.00 otherwise its working fine on rest
if(pos == -1)
{
document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount + ".00";
}
else
{
var integer = enterCheckAmount.substring(0,pos);
var decimals = enterCheckAmount.substring(pos+1);
while(decimals.length<2) decimals=decimals+'0';
enterCheckAmount = integer + '.' + decimals;
document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount;
}
JavaScript doesn't have a variable type for decimal numbers. It has only Number. If you want to display an integer as a decimal number with two zeros after the decimal point you can use the method toFixed.
Here is an example:
var myNumber = 11;
var myDecimalNumber = myNumber.toFixed(2);
console.log(myDecimalNumber) // will output 11.00
Thus there is no need to concatenate strings and add ".00" manually to your number.
Beyond this you can use the methods parseInt and parseFloat. Let's say you have a variable of type string with the value "11 pieces". You can get the integer with this line of code:
var myString = "11 pieces";
var myInteger = parseInt(myString, 10);
console.log(myInteger); // will output 11
If you have something similar like this, you are better off with this methods instead of cuting substrings.
I wish you a lot of success in refactoring your code and a warm welcome to the StackOverflow community.

Number converted in 1e+30

How to convert 1e+30 to 1000000000000000000000000000000
I want number as it is entered by User do not convert like 1e+30.
How can achieve this? Is there any way to display actual digits after parse it to float or int?
The core library doesn't give you any support for numbers that don't fit into the native number type, so you'll probably want to use a third party library to help you with large decimals.
For example, https://mikemcl.github.io/decimal.js/
new Decimal('1e+30').toFixed()
// "1000000000000000000000000000000"
You may use toLocaleString
(1000000000000000000000000000000).toLocaleString("en-US", { useGrouping: false })
You can make use of new Array() and String.replace, but it will only be in the form of String
function toNum(n) {
var nStr = (n + "");
if(nStr.indexOf(".") > -1)
nStr = nStr.replace(".","").replace(/\d+$/, function(m){ return --m; });
return nStr.replace(/(\d+)e\+?(\d+)/, function(m, g1, g2){
return g1 + new Array(+g2).join("0") + "0";
})
}
console.log(toNum(1e+30)); // "1000000000000000000000000000000"
Now it's more robust as it doesn't fail even if a really huge number such as 12e100 which will be converted to 1.2e+101, is provided as the . is removed and the last set of digits decremented once. But still 100% accuracy can't be ensured but that is because of limitations of floatation maths in javascript.

Javascript: Convert a string representation of money to Number

Lets say I have an amount in string format like this:
amount = '12,000.00'
I want to convert it into a Number (Javascript) or a float.
parseFloat(amount) // this gives me 12 as a result
Number(amount) // this gives me NaN as a result
Other solution I thought was this:
parseFloat(amount.replace(/[,]/g, ''))
This works fine. But the problem here is the Locale.
This would fail when the amount is € 12000,00.
Here ',' has altogether a different meaning.
I looked around for a good solution but couldn't. I am looking for a generalized solution.
This is not that easy, as you can't exactly know what's the delimiter for thousands and what for the decimal part
Consider "12.000.000" is it 12000.000 === 12000 or 12000000?
But if you would set the requirement that the last delimiter is always the decimal delimiter -
meaning if at least one delimiter is given, the last one has to be the decimal delimiter, *if the digits following, don't exceed a defined length.
Then you could try the following
Edit
(see the revs if you're interested in the old function)
I put in the ability to define the max length of digits after the last delimiter "," or "." up until it is treated as float, after that its returned as integer
var amounts = ["12000","12.000,00", "12,000.00", "12,000,01", "12.000.02", "12,000,001"];
formatMoney.maxDecLength = 3; //Set to Infinity o.s. to disable it
function formatMoney(a) {
var nums = a.split(/[,\.]/);
var ret = [nums.slice(0, nums.length - 1).join("")];
if (nums.length < 2) return +nums[0];
ret.push(nums[nums.length - 1]);
return +(ret.join(nums[nums.length - 1].length < formatMoney.maxDecLength ? "." : ""));
}
for ( var i=0,j;j=amounts[i];i++)
console.log (j + " -> " +formatMoney(j));
Gives the output:
"12000 -> 12000"
"12.000,00 -> 12000"
"12,000.00 -> 12000"
"12,000,01 -> 12000.01"
"12.000.02 -> 12000.02"
"12,000,001 -> 12000001" //as you can see after the last "," there are 3 digits and its treated as integer
Another JSBin
You can get the local decimal delimiter in this manner:
1.1.toLocaleString().substr(1,1)
Before parse float, you could make sure the string contains nothing but numbers, possibly a minus sign, and the local decimal delimiter.
The truth is, you'll never know the format. 12,345. Is that 12345, or another locale version if 12.345?
However, if you have consistent decimals, then you'd be able to use the lastIndexOf function on a comma and a period will reveal the decimal position and character.
var price = '12,345.67';
var lastPeriod = price.lastIndexOf('.');
var lastComma = price.lastIndexOf(',');
if (lastComma != -1 && lastComma > lastPeriod) {
decimalCharacter = ',';
} else {
decimalCharacter = '.';
}
console.log(decimalCharacter); //. or , based on how the price string looks - see below
If price is 12,345.67, decimalCharacter will be .. If it's 12.345,67, it'll be returned as ,.

Is there "0b" or something similar to represent a binary number in Javascript

I know that 0x is a prefix for hexadecimal numbers in Javascript. For example, 0xFF stands for the number 255.
Is there something similar for binary numbers ? I would expect 0b1111 to represent the number 15, but this doesn't work for me.
Update:
Newer versions of JavaScript -- specifically ECMAScript 6 -- have added support for binary (prefix 0b), octal (prefix 0o) and hexadecimal (prefix: 0x) numeric literals:
var bin = 0b1111; // bin will be set to 15
var oct = 0o17; // oct will be set to 15
var oxx = 017; // oxx will be set to 15
var hex = 0xF; // hex will be set to 15
// note: bB oO xX are all valid
This feature is already available in Firefox and Chrome. It's not currently supported in IE, but apparently will be when Spartan arrives.
(Thanks to Semicolon's comment and urish's answer for pointing this out.)
Original Answer:
No, there isn't an equivalent for binary numbers. JavaScript only supports numeric literals in decimal (no prefix), hexadecimal (prefix 0x) and octal (prefix 0) formats.
One possible alternative is to pass a binary string to the parseInt method along with the radix:
var foo = parseInt('1111', 2); // foo will be set to 15
In ECMASCript 6 this will be supported as a part of the language, i.e. 0b1111 === 15 is true. You can also use an uppercase B (e.g. 0B1111).
Look for NumericLiterals in the ES6 Spec.
I know that people says that extending the prototypes is not a good idea, but been your script...
I do it this way:
Object.defineProperty(
Number.prototype, 'b', {
set:function(){
return false;
},
get:function(){
return parseInt(this, 2);
}
}
);
100..b // returns 4
11111111..b // returns 511
10..b+1 // returns 3
// and so on
If your primary concern is display rather than coding, there's a built-in conversion system you can use:
var num = 255;
document.writeln(num.toString(16)); // Outputs: "ff"
document.writeln(num.toString(8)); // Outputs: "377"
document.writeln(num.toString(2)); // Outputs: "11111111"
Ref: MDN on Number.prototype.toString
As far as I know it is not possible to use a binary denoter in Javascript. I have three solutions for you, all of which have their issues. I think alternative 3 is the most "good looking" for readability, and it is possibly much faster than the rest - except for it's initial run time cost. The problem is it only supports values up to 255.
Alternative 1: "00001111".b()
String.prototype.b = function() { return parseInt(this,2); }
Alternative 2: b("00001111")
function b(i) { if(typeof i=='string') return parseInt(i,2); throw "Expects string"; }
Alternative 3: b00001111
This version allows you to type either 8 digit binary b00000000, 4 digit b0000 and variable digits b0. That is b01 is illegal, you have to use b0001 or b1.
String.prototype.lpad = function(padString, length) {
var str = this;
while (str.length < length)
str = padString + str;
return str;
}
for(var i = 0; i < 256; i++)
window['b' + i.toString(2)] = window['b' + i.toString(2).lpad('0', 8)] = window['b' + i.toString(2).lpad('0', 4)] = i;
May be this will usefull:
var bin = 1111;
var dec = parseInt(bin, 2);
// 15
No, but you can use parseInt and optionally omit the quotes.
parseInt(110, 2); // this is 6
parseInt("110", 2); // this is also 6
The only disadvantage of omitting the quotes is that, for very large numbers, you will overflow faster:
parseInt(10000000000000000000000, 2); // this gives 1
parseInt("10000000000000000000000", 2); // this gives 4194304
I know this does not actually answer the asked Q (which was already answered several times) as is, however I suggest that you (or others interested in this subject) consider the fact that the most readable & backwards/future/cross browser-compatible way would be to just use the hex representation.
From the phrasing of the Q it would seem that you are only talking about using binary literals in your code and not processing of binary representations of numeric values (for which parstInt is the way to go).
I doubt that there are many programmers that need to handle binary numbers that are not familiar with the mapping of 0-F to 0000-1111.
so basically make groups of four and use hex notation.
so instead of writing 101000000010 you would use 0xA02 which has exactly the same meaning and is far more readable and less less likely to have errors.
Just consider readability, Try comparing which of those is bigger:
10001000000010010 or 1001000000010010
and what if I write them like this:
0x11012 or 0x9012
Convert binary strings to numbers and visa-versa.
var b = function(n) {
if(typeof n === 'string')
return parseInt(n, 2);
else if (typeof n === 'number')
return n.toString(2);
throw "unknown input";
};
Using Number() function works...
// using Number()
var bin = Number('0b1111'); // bin will be set to 15
var oct = Number('0o17'); // oct will be set to 15
var oxx = Number('0xF'); // hex will be set to 15
// making function convTo
const convTo = (prefix,n) => {
return Number(`${prefix}${n}`) //Here put prefix 0b, 0x and num
}
console.log(bin)
console.log(oct)
console.log(oxx)
// Using convTo function
console.log(convTo('0b',1111))

Categories

Resources