How to force an integer into two digits exactly in JavaScript? - javascript

The problem is from my trying to convert number into a time format. I'd like to put time like "8:5" into "08:05". Any elegant JavaScript code?

Use split, map, slice and join
"8:5".split(":").map((s)=>("0"+s).slice(-2)).join(":"); //prints 08:05
You can invoke this at the blur/change event of your input box.

Related

What's the best way to print out a long number with dots in javascript?

I would like to print out millions(or more) like 321.100.401 . Do you have any good method?
If you don't need it to use periods as the separator, toLocaleString will convert a number to a string using the current locale.
var num = 5000;
console.log(num.toLocaleString());
Just take Number.prototype.toLocaleString with an appropriate parameter like 'de-DE'.
document.write((321100401).toLocaleString('de-DE'));

How to "unformat" a numerical string? JavaScript

So I know how to format a string or integer like 2000 to 2K, but how do I reverse it?
I want to do something like:
var string = "$2K".replace("/* K with 000 and remove $ symbol in front of 2 */");
How do I start? I am not very good regular expressions, but I have been taking some more time out to learn them. If you can help, I certainly appreciate it. Is it possible to do the same thing for M for millions (adding 000000 at the end) or B for billions (adding 000000000 at the end)?
var string = "$2K".replace(/\$(\d+)K/, "$1000");
will give output as
2000
I'm going to take a different approach to this, as the best way to do this is to change your app to not lose the original numeric information. I recognize that this isn't always possible (for example, if you're scraping formatted values...), but it could be useful way to think about it for other users with similar question.
Instead of just storing the numeric values or the display values (and then trying to convert back to the numeric values later on), try to update your app to store both in the same object:
var value = {numeric: 2000, display: '2K'}
console.log(value.numeric); // 2000
console.log(value.display); // 2K
The example here is a bit simplified, but if you pass around your values like this, you don't need to convert back in the first place. It also allows you to have your formatted values change based on locale, currency, or rounding, and you don't lose the precision of your original values.

Regex - creating an input/textarea that correctly interprets numbers

Im designing a conversion website where i perform calculations on inputted numbers and i need my input or textarea to receive and interpret numbers entered in different fashions
like:
Entry = 3,000,000.1111
Interpreted value = 3000000.1111
or
Entry = 3000000.1111
Interpreted value = 3000000.1111
and I want to include a second input for European decimal notation
(or if possible have the same input do both)
Entry = 3.000.000,1111 (comma acts a decimal, decimal as separator)
Interpreted value = 3000000.1111
I wonder how I could do this. I suspect from some of my research that I could use regex.
Also should i use an input or a textarea? I want to limit the size of the number to 40 places.
It seems the textarea Im currently using won't recognize any values after a comma when a comma is used. I realized this is due to parseFloat. So I need to remove the commas using .replace() before parsing. But what do I do in the instance of European notation where the comma IS the decimal point? I suspect I should use regex to identify if a number is in comma decimal notation or standard decimal point notation and then outline the appropriate replacement behavior based on that. Any ideas how to write regex to identify a number between .0000000001 and 1,000,000,000,000,000 by only the separator and decimal point? What about when the entry doesn't use either? 12000 for example. Any help with this would be appreciated. Using HTML5 and Javascript. I am not using a form and am new at this. This is my first web page so please be patient with my questions.
I was thinking about this:
input = //value from textarea as a string
if(/REGEX which determines that the structure of the number is N,NNN.NN/.test(input)){
input = input.replace(/\,/,""); //replace the commas with nothing
}
else if(/REGEX which determine that structure of the number is N.NNN,NN/.test(input){
input = input.replace(/\./,""); //replace the decimal point separators with nothing
input = input.replace(/\,/,".");//replace the comma decimal with a point decimal
}
else{
//input unchanged assuming is NNNN without decimal
}
number = parseFloat(input);
I want to keep the possibility open for them to enter large numbers and also to use numbers less than one to 10 decimal places. Thanks to those who contributed.
Best,RP
I believe this should handle everything:
^[1-9](?:\d{0,2}(?:([,.])\d{3})*|\d+)(?:(?!\1)[,.]\d+)?$
You're treading on complicated territory here. Also, the above RegEx does not allow for values less than "1".
Basically, the RegEx does the following:
Allows for no thousandths separators ("," or ".") but ensures if they are used that they occur in the correct places.
Allows for either "," or "." to be used as both thousandths/cents separators, but ensures that the cents separator is not the same as the thousandths separator.
Requires the string equivalent number to begin with any digit other than "0".
To implement this you could attach an event listener to your form element(s) and use JS to do a simple .test.
After reading further, I think I misinterpreted your goal originally. I assumed you simply wanted to validate these values with a RegEx. I also assumed you're trying to work with currency (ie. two decimal places). However, fret not! You can still utilize my original answer if you really want.
You mentioned input and textarea which are both form elements. You can attach a listener to these element(s) looking for the input, change, and/or keyup events. As a part of the callback you can run the .test method or some other functionality. Personally, I would rethink how you want to handle input. Also, what's your actual goal here? Do you really need to know the thousandths separator or keep track of it? Why not just disallow any characters other than the one decimal point/comma and digits?
Also, parsing numbers like .0000000001 as a float is a terrible idea. You will lose precision very quickly if you do any sort of calculations such as multiplication, division, power, etc. You're going to have to figure out a different method to do this like storing the number to the right separately and as integers instead then go from there.
I can help you if you describe what you're trying to do in better detail.

How to round off 9999999999999999 to 9999999999999998

In my case, i am converting a string value of '9999999999999999' to integer using parseFloat(). But it converts to next number of it i.e. 10000000000000000. But i need to convert it to before of that number i.e. 999999999999999998. I have searched for a while in google. But could not get clear idea to implement this.
Try this
document.getElementById("demo").innerHTML=Math.round(9999999999999999-2);
OUTPUT
9999999999999998
This number is too big to represented precisely in JavaScript Number value. So no amount of conversion will give you values reliably/precisly as you want around such range.
I.e. (9999999999999999-1)===(9999999999999999) returns true, but (9999999999999998)===(9999999999999999) returns false.
If you need such high precision in JavaScript (similar to many other languages) you need to use specialized data types (unfortunately there is no "BigInteger" type built in in JavaScript).
You will need to use some external javascript library to work with big numbers like that, cause max number you cant represent without losing presicion in javascript integers is 9007199254740992 (Explanation : What is JavaScript's highest integer value that a Number can go to without losing precision?)
Here you have some link where people discuss about some libraries to use for javascript big numbers.
How to deal with big numbers in javascript

JavaScript Concat

Via jquery / Javascript
Given a number 1234567891234
How can I concat, or truncast By removing the 2 from the left to make that number a valid integer I can insert into MySQL:'
4567891234
Thanks
This question edited by someone other than the OP, who's trying to guess at what the OP wants. Bear this in mind, but I think he wants to know:
How can I remove the first two characters from a string, using jQuery?
Assuming they want a substring of the original number:
var result = String(1234567891234).substr(2);
console.log(result); // Should be 34567891234
A crossbrowser way:
(1234567891234).toString().slice(2);

Categories

Resources