JavaScript number formatting with point for thousand and comma for decimals - javascript

I have a web application with some calculations in text fields. Application is worked in asp.net using vb. I have JavaScript that need to do some calculations every time onTextChange action.
For example I have to enter a number in this format 123.123 or 123 and at the end I want to calculate all text fields and to do formatting like this 123.123,00 or 123,00
For now I am using:
document.getElementById('<%=FV.FindControl("txtSUM").ClientID%>').value = ("" + sum).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, function ($1) { return $1 + "." });
but this only adding a point on thousand, apart from that I want to add and comma on decimal place.

Related

Regex to make nondecimal number decimal (add .00)

I have an user input where user can edit price of something. To leave data consistance I would like to manipulate with that string on front-end site.
What I want to do is:
1234 to 1234.00
12.3 to 12.30
12,3 to 12.30
1234.45 to 1234.45
So basicly,
Replace comma with dots
this should be done easy with somehing like:
str.replace(',', '.');
Add dots if number if not decimal and also always change number of digits on two(so add 0 if needed)
I try to do something like:
priceByUser = priceByUser.replace(/^\d*\.?\d*$/, "$1\.00");
unfortunately this really doesnt even work as I expected.
Is there a chance someone can help me to solve this issue?
Thanks
You could consider using a regular expression to replace your commas and periods with just decimal points and then parse the values as floats via parseFloat() then finally, use the toFixed(2) function to indicate that you want two decimal places :
// This will clean up your input (consolidating periods and commas), parse the result
// as a floating point number and then format that number to two decimal places
priceByUser = parseFloat(priceByUser.replace(/,/g,'.')).toFixed(2);
If you wanted an extra-level of validation, you could consider stripping out any non-digit or decimal places after this occurs :
// Sanitize
priceByUser = priceByUser.replace(/,/g,'.').replace(/[^\d\.]/g,'');
// Parse and format
priceByUser = Number(priceByUser).toFixed(2);
Example
You can see a working example here and and example of input/output below :

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.

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".

Excel to XML: Round decimals to the nearest hundredth and keep hyperlinks

I followed this guide to export an Excel Spreadsheet as an XML data file and then this guide to display the XML sheet as an HTML table on my website. It worked great. Now I "only" have to small issues remaining that I couldn't get solved.
(1) The output table contains numbers like 1.325667 but also lots of 0s. I would like the zeroes to be displayed as 0.00 and the numbers with many decimals to be displayed as 1.33. Basically, each number should be displayed with two decimals.
(2) The excel sheet contains hyperlinks to other pages on my website that I would like to keep when rendering the XML data file and then the HTML table. So far, that didn't work. Is this possible?
UPDATE I figured this part out. By breaking up the hyperlinks in just their character-strings, then adding new columns for these character strings, and then tweaking the source code to including
document.write("<tr><td><a href='");
document.write(x[i].getElementsByTagName("character-string")0].childNodes[0].nodeValue);
document.write(".php'>");
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
document.write("</a></td>");
I was able to include hyperlinks.
The Excel-Sheet is formatted with these two aspects already integrated, but the conversion to an XML file seems to be the problem.
Thank you so much for your help (again and again :-))
UPDATE I now also found a way to do the rounding in Excel, but I'm still stuck with integers and numbers with only one decimal. Basically, I now "only" need a way to show every number with two decimal points, applying to integers (e.g. 0 should 0.00) and numbers with one decimal (e.g. 1.5 should be 1.50). JohnnyReeves' answer seems to be on the right track but I couldn't get it to work. Any other ideas?
The Number Object has the method toFixed():
1.325667.toFixed(2) = 1.33.
Running inside the loop of the XML, select the URL and add it to the link:
document.write("< a href=" + x[i].getElementsByTagName(< your URL link>) + ">);
document.write("some text");
document.write("< /a>");
The Number.toFixed method will only work on floating point values (eg: 2.1), but not on integers (eg: 2, or 0). You will need to convert your number type to a string type so you can format it for display and get consistent results regardless of the input. A function like this should do the trick:
function formatNumber(value) {
var parts,
trailingDigits,
formattedRemainder;
// Coerce the supplied value to a String type.
value = String(value);
// Break the supplied number into two parts, before and after the dot
parts = value.split(".");
// If there was no dot, there will only be one "part" and we can just
// add the trailing zeros.
if (parts.length === 1) {
formattedRemainder = "00";
}
else {
trailingDigits = parts[1];
if (trailingDigits.length === 0) {
// A dot, but no digits. (eg: 2. -> 2.00)
formattedRemainder = "00";
}
else if (trailingDigits.length === 1) {
// Add an extra trailing zero (eg: 2.1 -> 2.10)
formattedRemainder = trailingDigits + "0";
}
else {
// Just take the last two trailing digits.
formattedRemainder = trailingDigits.substring(0, 2);
}
}
// Build the final formatted string for display.
return parts[0] + "." + formattedRemainder;
}

Only allow a single dot point in input field

I have an input field which has:
$(".double").alphanumeric({allow:" ",ichars:"`~!##$%^&*=_+[]\\{}|;\":,/<>?'-()\/abcdefghijklmnopqrstuvwxyzABCDFEGHIJKLMNOPQRSTUVWXYZ"});
validation applied to it.
I need to further restrict entry so that only a single decimal place can be added e.g. 100.00 or 255.95
The input is used for currency so I need to only allow 1 decimal point. At the moment its allow 100.00.00 which messes up the system!
Thanks
Here is a regex that will only allow positive/negative decimal numbers
^[-]?((\d+)|(\d+\.\d+)|(\.\d+))$
With jquery you can test the value
if (/^[-]?((\d+)|(\d+\.\d+)|(\.\d+))$/.test($(".double").val())) { .... }
A simple function to allow an optional leading + or - and only digits with an optional decimal place is:
function validate(value) {
var re = /^[-+]?\d+(\.\d+)?$/;
return re.test(value);
}
However since you want money, you might want:
var re = /^[-+]?\d+(\.\d\d)?$/;
which will require two digits after the decimal place, if there is one.

Categories

Resources