Add a decimal to a string - javascript

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

Related

What's the fastes way to take big numbers (e.g. 1900234) and put commas after every three digits?

I am working on an internship project that, although it's not focused on performance, I would want to be as fast (and lean) as possible. So far, I have one working version (with a bug) and one concept of the aforementioned function:
V1 (BUG: Can't handle numbers with dots and commas.)
function addCommas(nStr) {
if (isNaN(nStr)) {
throw new Error(`${nStr} is NaN`);
}
// Alternative: isNaN(nStr) ? throw new Error(`${nStr} is NaN`) : nStr += ``;
nStr += ``;
// If the input is of the form 'xxxx.yyy', split it into x1 = 'xxxx'
// and x2 = '.yyy'.
let x = nStr.split(`.`);
let x1 = x[0];
let x2 = x.length > 1 ? `.` + x[1] : ``;
let rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
// x1 takes the form 'x,xxx' - no matter how long the number,
// this is where the commas are added after every three digits.
x1 = x1.replace(rgx, `$1` + `,` + `$2`);
}
return x1 + x2;
}
V2 Concept (looks slower but no known bugs)
function addCommas(nStr) {
if (isNaN(nStr)) {
throw new Error(`${nStr} is NaN`);
}
nStr += ``;
// Remove any potential dots and commas.
nStr = nStr.replace(`.`, ``);
nStr = nStr.replace(`,`, ``);
// Split the number into an array of digits using String.prototype.split().
// Iterate digits. After every three, add a comma.
// Transform back into a string.
return nStr;
}
Check out the function toLocaleString:
const b = 5120312039;
console.log(b.toLocaleString()); //"5,120,312,039"
Try this
var str = "123456789";
var result = [...str].map((d, i) => i % 3 == 0 && i > 0 ? ','+d : d).join('').trim();
console.log(result);

Printing floating point values with decimals and not with e-notation in JavaScript

When i print a floating point like 0.0000001 in JavaScript it gives me
1e-7
how can i avoid that and instead print it "normally" ?
You can use this:
var x = 0.00000001;
var toPrint = x.toFixed(7);
This sets toPrint to a string representation of x with 7 digits to the right of the decimal point. To use this, you need to know how many digits of precision you need. You will also need to trim off any trailing 0 digits if you don't want them (say, if x was 0.04).
function noExponent(n){
var data= String(n).split(/[eE]/);
if(data.length== 1) return data[0];
var z= '', sign= +n<0? '-':'',
str= data[0].replace('.', ''),
mag= Number(data[1])+ 1;
if(mag<0){
z= sign + '0.';
while(mag++) z += '0';
return z + str.replace(/^\-/,'');
}
mag -= str.length;
while(mag--) z += '0';
return str + z;
}
I've got a simple solution that appears to be working.
var rx = /^([\d.]+?)e-(\d+)$/;
var floatToString = function(flt) {
var details, num, cnt, fStr = flt.toString();
if (rx.test(fStr)) {
details = rx.exec(fStr);
num = details[1];
cnt = parseInt(details[2], 10);
cnt += (num.replace(/\./g, "").length - 1); // Adjust for longer numbers
return flt.toFixed(cnt);
}
return fStr;
};
floatToString(0.0000001); // returns "0.0000001"
EDIT Updated it to use the toFixed (didn't think about it).
EDIT 2 Updated it so it will display numbers 0.0000000123 properly instead of chopping off and showing "0.00000001".

js add comma at Sextillion values

I use one small code js to add comma to value:
function addCommas(nStr)
{
nStr += '';
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;
}
I have problem when try to add comma to big values like sextillion values.
Eg.
addCommas(1000000) //return correct "1,000,000"
but if use big values like this
addCommas(50949024266983356472874) // return wrong "5.094902426698335e+22"
What or where I do wrong?
Your input might already be a float. Numbers larger than 2^32 tend to be like this. Make sure your input is a string and your function will run fine.
JavaScript doesn't have int and float types. Instead it just has a Number type and it will decide on it's own when to use which.
When you do
nStr += '';
You're asking javascript to first convert your number to a string. That's when it decides to write it as "5.094902426698335e+22". The problem isn't in the rest of your algorithm.
The conversion is described here in ecmascript
If your number is stored in a string the following function will achieve what you are asking for.
function addCommas( txtNum ) {
var parts = txtNum.split(".");
parts[0] = parts[0].reverse().replace(/(\d{3})/g, "$1,").reverse();
return parts.join(".");
}
String.prototype.reverse = function () {
return this.split("").reverse().join("");
}
addCommas( "-50000000000000000000000000000000000000000.0000" );
// => -50,000,000,000,000,000,000,000,000,000,000,000,000,000.0000

Adding extra zeros in front of a number using jQuery?

I have file that are uploaded which are formatted like so
MR 1
MR 2
MR 100
MR 200
MR 300
ETC.
What i need to do is add extra two 00s before anything before MR 10 and add one extra 0 before MR10-99
So files are formatted
MR 001
MR 010
MR 076
ETC.
Any help would be great!
Assuming you have those values stored in some strings, try this:
function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
pad("3", 3); // => "003"
pad("123", 3); // => "123"
pad("1234", 3); // => "1234"
var test = "MR 2";
var parts = test.split(" ");
parts[1] = pad(parts[1], 3);
parts.join(" "); // => "MR 002"
I have a potential solution which I guess is relevent, I posted about it here:
https://www.facebook.com/antimatterstudios/posts/10150752380719364
basically, you want a minimum length of 2 or 3, you can adjust how many 0's you put in this piece of code
var d = new Date();
var h = ("0"+d.getHours()).slice(-2);
var m = ("0"+d.getMinutes()).slice(-2);
var s = ("0"+d.getSeconds()).slice(-2);
I knew I would always get a single integer as a minimum (cause hour 1, hour 2) etc, but if you can't be sure of getting anything but an empty string, you can just do "000"+d.getHours() to make sure you get the minimum.
then you want 3 numbers? just use -3 instead of -2 in my code, I'm just writing this because I wanted to construct a 24 hour clock in a super easy fashion.
Note: see Update 2 if you are using latest ECMAScript...
Here a solution I liked for its simplicity from an answer to a similar question:
var n = 123
String('00000' + n).slice(-5); // returns 00123
('00000' + n).slice(-5); // returns 00123
UPDATE
As #RWC suggested you can wrap this of course nicely in a generic function like this:
function leftPad(value, length) {
return ('0'.repeat(length) + value).slice(-length);
}
leftPad(123, 5); // returns 00123
And for those who don't like the slice:
function leftPad(value, length) {
value = String(value);
length = length - value.length;
return ('0'.repeat(length) + value)
}
But if performance matters I recommend reading through the linked answer before choosing one of the solutions suggested.
UPDATE 2
In ES6 the String class now comes with a inbuilt padStart method which adds leading characters to a string. Check MDN here for reference on String.prototype.padStart(). And there is also a padEnd method for ending characters.
So with ES6 it became as simple as:
var n = '123';
n.padStart(5, '0'); // returns 00123
Note: #Sahbi is right, make sure you have a string otherwise calling padStart will throw a type error.
So in case the variable is or could be a number you should cast it to a string first:
String(n).padStart(5, '0');
function addLeadingZeros (n, length)
{
var str = (n > 0 ? n : -n) + "";
var zeros = "";
for (var i = length - str.length; i > 0; i--)
zeros += "0";
zeros += str;
return n >= 0 ? zeros : "-" + zeros;
}
//addLeadingZeros (1, 3) = "001"
//addLeadingZeros (12, 3) = "012"
//addLeadingZeros (123, 3) = "123"
This is the function that I generally use in my code to prepend zeros to a number or string.
The inputs are the string or number (str), and the desired length of the output (len).
var PrependZeros = function (str, len) {
if(typeof str === 'number' || Number(str)){
str = str.toString();
return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
}
else{
for(var i = 0,spl = str.split(' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(' '):str,i++);
return str;
}
};
Examples:
PrependZeros('MR 3',3); // MR 003
PrependZeros('MR 23',3); // MR 023
PrependZeros('MR 123',3); // MR 123
PrependZeros('foo bar 23',3); // foo bar 023
If you split on the space, you can add leading zeros using a simple function like:
function addZeros(n) {
return (n < 10)? '00' + n : (n < 100)? '0' + n : '' + n;
}
So you can test the length of the string and if it's less than 6, split on the space, add zeros to the number, then join it back together.
Or as a regular expression:
function addZeros(s) {
return s.replace(/ (\d$)/,' 00$1').replace(/ (\d\d)$/,' 0$1');
}
I'm sure someone can do it with one replace, not two.
Edit - examples
alert(addZeros('MR 3')); // MR 003
alert(addZeros('MR 23')); // MR 023
alert(addZeros('MR 123')); // MR 123
alert(addZeros('foo bar 23')); // foo bar 023
It will put one or two zeros infront of a number at the end of a string with a space in front of it. It doesn't care what bit before the space is.
Just for a laugh do it the long nasty way....:
(NOTE: ive not used this, and i would not advise using this.!)
function pad(str, new_length) {
('00000000000000000000000000000000000000000000000000' + str).
substr((50 + str.toString().length) - new_length, new_length)
}
I needed something like this myself the other day, Pud instead of always a 0, I wanted to be able to tell it what I wanted padded ing the front. Here's what I came up with for code:
function lpad(n, e, d) {
var o = ''; if(typeof(d) === 'undefined'){ d='0'; } if(typeof(e) === 'undefined'){ e=2; }
if(n.length < e){ for(var r=0; r < e - n.length; r++){ o += d; } o += n; } else { o=n; }
return o; }
Where n is what you want padded, e is the power you want it padded to (number of characters long it should be), and d is what you want it to be padded with. Seems to work well for what I needed it for, but it would fail if "d" was more than one character long is some cases.
var str = "43215";
console.log("Before : \n string :"+str+"\n Length :"+str.length);
var max = 9;
while(str.length < max ){
str = "0" + str;
}
console.log("After : \n string :"+str+"\n Length :"+str.length);
It worked for me !
To increase the zeroes, update the 'max' variable
Working Fiddle URL : Adding extra zeros in front of a number using jQuery?:
str could be a number or a string.
formatting("hi",3);
function formatting(str,len)
{
return ("000000"+str).slice(-len);
}
Add more zeros if needs large digits
In simple terms we can written as follows,
for(var i=1;i<=31;i++)
i=(i<10) ? '0'+i : i;
//Because most of the time we need this for day, month or amount matters.
Know this is an old post, but here's another short, effective way:
edit: dur. if num isn't string, you'd add:
len -= String(num).length;
else, it's all good
function addLeadingZeros(sNum, len) {
len -= sNum.length;
while (len--) sNum = '0' + sNum;
return sNum;
}
Try following, which will convert convert single and double digit numbers to 3 digit numbers by prefixing zeros.
var base_number = 2;
var zero_prefixed_string = ("000" + base_number).slice(-3);
By adding 100 to the number, then run a substring function from index 1 to the last position in right.
var dt = new Date();
var month = (100 + dt.getMonth()+1).toString().substr(1, 2);
var day = (100 + dt.getDate()).toString().substr(1, 2);
console.log(month,day);
you will got this result from the date of 2020-11-3
11,03
I hope the answer is useful

having problems adding commas to number while limiting it to only 2 decimal places

function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
P = addCommas(P);
$("#monthly_result").html(P.toFixed(2));
I left out the P calculations, so keep in mind it is outputting a number in the thousands with decimals.
I got the function from stack and it works well adding commas to numbers in the thousands. However when I tried to limit the value to 2 decimal places it doesnt output anything.
Thanks
my answer is pretty simple but would be what your looking for:
http://phpjs.org/functions/number_format:481
Example:
$("#monthly_result").html(number_format('1234.56', 2));
toFixed is not available for strings (which your addCommas function returns).
simple solution would be to convert the number to a float by using parseFloat and then cut the decimal places using toFixed and convert back to string to proceed with your function.
for a fixed number of decimal places, something along the lines of:
function addCommas(num) {
var num = parseFloat(num).toFixed(2)+'',
rgx = /(\d+)(\d{3}[\d,]*\.\d{2})/;
while (rgx.test(num)) {
num = num.replace(rgx, '$1' + ',' + '$2');
}
return num;
}
In this case, addCommas(61423.34512); would return "61,423.35". I'd recommend using the number_format function posted by Robert for some extra formatting options, though.

Categories

Resources