How do I retain leading zeroes in an Integer/Number in JavaScript? - javascript

I am trying to retain leading zeroes in an integer/number within JavaScript.
In this example I have an "ItemName" key which has either a string or an integer as its value.
I only want to have integers to be the value, but when I try converting any string value to a number, it will remove the leading zeroes.
I need to retain the zeroes so that the data sent will reliably be 6 digits, where in the example it would only be 4 digits.
The value is intended to be an identifier for a given Item.
{"Item": [{"ItemName":"007730","BusinessUnit":1}] }
{"Item": [{"ItemName":917730,"BusinessUnit":1}] }
This is for my work and we use ES6, but if there's an option outside of that, I'm certainly open to it.
Thanks in advance!

You can't have a number with leading zeroes in Javascript, because, as Randy Casburn said, they don't have any value. You have to convert it to a string and use String.padStart() to pad the string with zeroes. parseInt will work with leading zeroes. For example:
(294).toString().padStart(6, "0") --> "000294"
parseInt("000294") --> 294

Related

regex check for Float number -> not ending and stars with decimal point

I am facing issues with regex pattern for Float number -> that should not end or stars with decimal points..
I have tried following regex patter.. that is
regex = /^\d*\.?\d*$/
// on doing
regex.test(11.)
regex.test(.11)
// it is returning true in checking
// I need to make this as false, comment will be much helpful
thank you.
You should bear in mind that regex only works with strings. When you pass a non-string variable as input to a RegExp, it will first coerce it to a string type.
Have a look:
console.log(11. , 'and', .11); // => 11 and 0.11
So, the actual string values you pass to your ^\d*\.?\d*$ regex are 11 and 0.11 that can be matched with the given pattern. Actually, ^\d*\.?\d*$ is a regex that is usually used for a very loose live number input validation, e.g. see How to make proper Input validation with regex?.
What you want is to implement a final, on-submit validation pattern, so that it could not pass strings like 11. and .11. There have been lots of threads discussing this kind of regex:
Regular expression for floating point numbers
regular expression for finding decimal/float numbers?
Basically, for validation, you will need something like
/^\d+(?:\.\d+)?$/.test(input_string)
/^[0-9]+(?:\.[0-9]+)?$/.test(input_string)
/^[0-9]+(?:\.[0-9]{1,2})?$/.test(input_string) // Some need to only allow 1 or 2 fractional digits
/^[0-9]{1,3}(?:\.[0-9]{2})?$/.test(input_string) // 1-3 digits in the integer part and two required in the fractional part

How to change this to a number and keep all digits

"07999323384"
How do I convert the number above to number, but once I use any numeric method it takes out the first zero
You use Number("07999323384"); except it will take out the first 0, its not possible to have a number beginning with 0 (except the number 0) because js removes leading 0s.
There is nothing you can do about this however that shouldnt matter because there should be no situation where you need it as a number type but also need the first 0
Create a copy in a seperate variable to do calculations on (which will drop the leading zero) and use the original variable to maintain the leading zero, it's either that or pad out the number after using your numeric methods presuming it's a fixed length as per this: How can I pad a value with leading zeros?

Round float to 2 decimals javascript

I have the problem that when i round a number to 2 decimals the parseFloat() function removes .00 from the number. I have tried
var num = parseFloat(Math.round(19 * 100) / 100).toFixed(2);
The return: num="19.00"
The return i need: num = 19.00
I know 19 = 19.00, but i am using a service that always require two decimals .00
The function returns a string with the right value. When i parse it to float the .00 is removed.
You cannot get 19.00 as float, only as string, because numbers always remove trailing zeros.
Maybe you can show us a bit more code to get an idea, there you need these trailing zeros?
Numbers do and can not hold information about their representation. They are only a numerical value.
When you display a number using window.alert, console.log or similar, you are not looking at a number, but at a string. Those display functions convert numbers to strings before displaying them. Number.toFixed also converts numbers into strings, with the difference being that it rounds them to two decimal places, so you end up with another representation of the same number.
What I am trying to say is that to display a number, you cannot get around converting it to a string. Whether you do it explicitly or the display function does it for you. When you send the number to the service that you are using, you are probably also sending a string (JSON, XML, etc. are always strings once you send them). If you need the value of the number for calculations, use it, then convert it in the end. No matter how, you have to do it in the end if you want those 0's at the end.

Add comma separator to a value variable

I have read some thousand comma separator JavaScript question/answer but found it hard to apply it in practice. For example I have the variable
x = 10023871234981029898198264897123897.231241235
How will I separate it in thousands with commas? I want a function that not only works with that number of digits but more. Regardless of the number of digits the function I need has to separate the number in commas and leaving the digits after the decimal point as it is, Can anyone help? It has to work on number and turn it into string.
First of all, for such huge numbers you should use string format:
var x = "10023871234981029898198264897123897.231241235";
Otherwise, JavaScript will automatically convert it to exponential notation, i.e. 1.002387123498103e+34.
Then, according to the question about money formatting, you can use the following code:
x.replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
It will result in: "10,023,871,234,981,029,898,198,264,897,123,897.231241235".

Javascript alert number starting with 0

I have a button where in the code behind I add a onclick and I pass a unique ID which will be passed to the js function. The id starts with a 0.
It wasn't working and eventually I figured out that the number, id, it was passing was wrong...
Ie. see this: js fiddle
It works with a ' at the start and end of the number. Just wondering why 013 turns to 11. I did some googling and couldn't find anything...
Cheers
Robin
Edit:
Thanks guys. Yep understand now.
As in this case the 0 at the start has a meaning, here the recipient ID in a mailing list, I will use '013' instead of just 013, i.e. a string. I can then split the values in js as each of the 3 values represents a different id which will always be only 1 character long, i.e. 0-9.
A numeric literal that starts with a 0 is treated as an octal number. So 13 from base 8 is 11 in base 10...
Octal numeric literals have been deprecated, but still work if you are not in strict mode.
(You didn't ask, but) A numeric literal that starts with 0x is treated as hexadecimal.
More info at MDN.
In your demo the parameter is called id, which implies you don't need to do numerical operations on it - if so, just put it in quotes and use it as a string.
If you need to be able to pass a leading zero but still have the number treated as base 10 to do numerical operations on it you can enclose it in quotes to pass it as a string and then convert the string to a number in a way that forces base 10, e.g.:
something('013');
function something(id){
alert(+id); // use unary plus operator to convert
// OR
alert(parseInt(id,10)); // use parseInt() to convert
}
Demo: http://jsfiddle.net/XYa6U/5/
013 is octal, not decimal, it's equal 11 in decimal
You should note that 013 starts with a 0. In Javascript, this causes the number to be considered octal. In general you'll want to use the decimal, and hexadecimal number systems. Occasionally though, octal numbers are useful, as this question shows.
I hope this helps! :)
If the first digit of a number is a zero, parseInt interprets the number as an octal.
You can specify a base of ten like this:
parseInt(numberString, 10)
You could also remove such zeros with a regex like this (the result will be a string):
numberString.replace(/^0+/g, '');

Categories

Resources