Calculations on formatted text fields - javascript

I have a form that will collect various data about properties. The user enters in values to select fields and onBlur, those values are formatted with comma's, dollar signs, and/or percentage signs.
I'm trying to create some real time calculations based on those inputs, but I'm having a hard time getting started on this. I have created a jfiddle page and have been playing around with ideas for the past few hours, but I just cannot seem to get the first calculation working.
I know I need to strip out any characters and have tried parseInt, parseFloat, replace, ect. Just nothing seems to work.
Thank you in advance.
function formatNumber(number, digits, decimalPlaces, withCommas)
{
number = number.toString();
var simpleNumber = '';
// Strips out the dollar sign and commas.
for (var i = 0; i < number.length; ++i)
{
if ("0123456789.".indexOf(number.charAt(i)) >= 0)
simpleNumber += number.charAt(i);
}
number = parseFloat(simpleNumber);
if (isNaN(number)) number = 0;
if (withCommas == null) withCommas = false;
if (digits == 0) digits = 1;
var integerPart = (decimalPlaces > 0 ? Math.floor(number) :
Math.round(number));
var string = "";
for (var i = 0; i < digits || integerPart > 0; ++i)
{
// Insert a comma every three digits.
if (withCommas && string.match(/^\d\d\d/))
string = "," + string;
string = (integerPart % 10) + string;
integerPart = Math.floor(integerPart / 10);
}
if (decimalPlaces > 0)
{
number -= Math.floor(number);
number *= Math.pow(10, decimalPlaces);
string += "." + formatNumber(number, decimalPlaces, 0);
}
return string;
}
function sumCalc() { // function to remove comma and then calculate
var glasf =
document.getElementById('gross_land_sf').value.replace(/,/g, "");
document.getElementById('gross_land_acre').value = formatNumber(glasf/43560);
}
https://jsfiddle.net/vva3x3wu/4/

Is this what you want ? I did some fixes:
https://jsfiddle.net/vva3x3wu/11/
In the link you put in the comment you removed class .cal from the first input, so calculations will not star until you tab from the last input.

Related

JS for-loop how to get the first value

I'm sorry for the dumb question. I've been trying to do this for hours now, and i really can't get it to work. So i have a for-loop that loops though some numbers.
But it doesn't take the first value(71990000).
How can this be achieved?
This is what i've got so far:
var minNr = 0000;
var maxNr = 10000;
var prefix = 7199;
function Nummer(min,max)
{
var regex = /^(\d{2})\1$/;
var guld_nr;
for(guld_nr = minNr; guld_nr < maxNr;)
{
if(regex.test(guld_nr))
{
$(".resultat").append(prefix + "" + guld_nr + "<br>");
}
guld_nr++;
}
}
The output is this:
71991010
71991111
71991212
71991313
But i also need the number: 71990000
How can i do that ?
It's because your regex is rejecting the number 0; the first time through the loop, minNr has the numeric value 0 (setting it to 0000 doesn't help; it's just a fancy way of saying 0). The regex expects two digits followed by the same pattern, but what you're giving it is the string '0'.
You could set minNr to be a string instead on the first pass through ('0000'), and this will solve the problem for '0000', but you will miss '0101', '0202', etc. (which will convert to the strings '101', '202', and so on.)
One solution would be to zero pad the string representation of your number. The following function will take any number and left zero pad it to fit a given width:
function zeropad(n, w) {
n = String(n);
while(n.length < w) n = '0' + n;
return n;
}
You can use it to convert minNr for the regex:
regex.test(zeropad(guld_nr, 4))
Also note that Number is a built-in object wrapper for literals in JavaScript (all of the primitives have object wrappers: Number, Boolean, String), and by creating a function called Number, you are occluding this built-in object, which is inadvisable (code that needs to use it will invoke your function instead, which is incompatible and has a different purpose).
Use string:
var minNr = '0000';
It's the start value for the regex test, and you need the four zeroes for that. If it would be a number, then you get only one zero for testing. it would help, if you pad it with leading zeroes.
var minNr = '0000',
maxNr = 10000,
prefix = 7199;
function Nummer(min,max) {
var regex = /^(\d{2})\1$/;
var guld_nr;
for(guld_nr = minNr; guld_nr < maxNr;guld_nr++) {
if(regex.test(guld_nr)) {
document.write(prefix + "" + guld_nr + "<br>");
}
}
}
Nummer(minNr, maxNr);
Numbers don't zero-pad themselves; 0000; // 0
Make a custom zero-pad method for it so you can do zpad(0, 4); // "0000"
function zpad(x, digits) {
var pad = '0';
x = x.toString();
digits -= x.length;
while (digits > 0) {
if (digits & 1) x = pad + x;
pad += pad;
digits >>>= 1;
}
return x;
}
Now adjust Nummer accordingly
function Nummer(min, max, prefix) {
var regex = /^(\d{2})\1$/,
i, str;
prefix = prefix || '';
for(i = min; i < max; ++i) {
str = zpad(i, 4);
if(regex.test(str)) console.log(prefix + str);
}
}
and use
Nummer(minNr, maxNr, '7199');
Side note
Nummer is not constructing an Object, consider camel casing it
You could use arithmetic to do the digit pattern check, and keep the result numerical:
var minNr = 0; // it does not help to put 4 zeroes here.
var maxNr = 10000;
var prefix = 7199;
function Nummer(min,max) {
for (var guld_nr = min; guld_nr < max; guld_nr++) {
if (Math.floor(guld_nr/100) === guld_nr % 100 ) {
$(".resultat").append((prefix * 10000 + guld_nr) + "<br>");
}
}
}
Nummer(minNr, maxNr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="resultat"></div>
The problem with your code is when the lower numbers are tested against the regular expression, they are implicitly converted to string, and do not get prefixed zeroes, so they fail on the regular expression.
Anyway, the code will be more efficient when sticking to numbers instead of strings, so I would suggest working with numbers all the way up to the point of outputting them in the browser.
Even more efficient is this code:
var minNr = 0; // it does not help to put 4 zeroes here.
var maxNr = 10000;
var prefix = 7199;
function Nummer(min,max) {
var test = Math.floor(min/100)*100 + Math.floor(min/100)%100;
var guld_nr = test < min ? test + 101 : test;
for (; guld_nr < max; guld_nr+=101) {
$(".resultat").append((prefix * 10000 + guld_nr) + "<br>");
}
}
Nummer(minNr, maxNr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="resultat"></div>

Converting input into nicely formatted numbers (javascript)

Two part question.
Part 1 is easy, but I'm wondering what you think is the most elegant solution:
What would be the best procedure to use to convert input into cleanly formatted and WITH "normal" comma placement. The input could range from:
$8000
8200
8,000.50
And I want it to output simply: 8,000
Part 2, may be easy I just don't know the right operation. I want to round numbers so that: it is rounded based on the number of digits. So that there are TWO unrounded digits at all time.
45,643 should be 46,000
453 should be 450
59,023,920 should be 59,000,000
The following code should answer both parts of the question:
var input = "$820322310"; // String input
input = input.replace(/[^0-9\.]/g, ""); // remove all unnecessary characters
input = input.replace(/\.[0-9]+/, ""); // remove all after decimal (convert to integer)
if(parseInt(input[2]) >= 5) { // rounding to two decimal places
input[1] = input.slice(0, 1) + (parseInt(input[1]) + 1) + input.slice(2, input.length);
}
var count = 0;
for(var i = input.length-1; i >= 0; i--) {
if(i > 2) {
input = input.slice(0, i-1) + "0" + input.slice(i, input.length);
}
if(++count == 3 && i != 0) {
count = 0;
input = input.slice(0, i) + "," + input.slice(i, input.length);
}
}
See this at JSFiddle.

Wrong Convert amount

The following function works perfect, but when the amount over 1 million, the function don't work exactly.
Example:
AMOUNTPAID = 35555
The output is: 35.555,00 - work fine
But when the amount paid is for example: 1223578 (over 1 Million),
is the output the following output value: 1.223.235,00 (but it must be: 1.223.578,00) - there is a deviation of 343
Any ideas?
I call the function via HTML as follows:
<td class="tr1 td2"><p class="p2 ft4"><script type="text/javascript">document.write(ConvertBetrag('{{NETAMOUNT}}'))</script> €</P></TD>
#
Here ist the Javascript:
function Convertamount( amount ){
var number = amount;
number = Math.round(number * Math.pow(12, 2)) / Math.pow(12, 2);
number = number.toFixed(2);
number = number.toString();
var negative = false;
if (number.indexOf("-") == 0)
{
negative = true ;
number = number.replace("-","");
}
var str = number.toString();
str = str.replace(".", ",");
// number before decimal point
var intbeforedecimaln = str.length - (str.length - str.indexOf(","));
// number of delimiters
var intKTrenner = Math.floor((intbeforedecimaln - 1) / 3);
// Leading digits before the first dot
var intZiffern = (intbeforedecimaln % 3 == 0) ? 3 : (intbeforedecimaln % 3);
// Provided digits before the first thousand separator with point
strNew = str.substring(0, intZiffern);
// Auxiliary string without the previously treated digits
strHelp = str.substr(intZiffern, (str.length - intZiffern));
// Through thousands of remaining ...
for(var i=0; i<intKTrenner; i++)
{
// attach 3 digits of the nearest thousand group point to String
strNew += "." + strHelp.substring(0, 3);
// Post new auxiliary string without the 3 digits being treated
strHelp = strHelp.substr(intZiffern, (strHelp.length - intZiffern));
}
// attach a decimal
var szdecimal = str.substring(intbeforedecimaln, str.length);
if (szdecimal.length < 3 )
{
strNew += str.substring(intbeforedecimaln, str.length) + '0';
}
else
{
strNew += str.substring(intbeforedecimaln, str.length);
}
var number = strNew;
if (negative)
{
number = "- " + number ;
}
return number;
}
JavaScript's Math functions have a toLocaleString method. Why don't you just use this?
var n = (1223578.00).toLocaleString();
-> "1,223,578.00"
The locale you wish to use can be passed in as a parameter, for instance:
var n = (1223578.00).toLocaleString('de-DE');
-> "1.223.578,00"

Add space separator to number in input box

I'm trying to get an input box to display numbers with space separator. Like this:
20 000 and 20 000 000 instead of 20000 and 20 000 000
The thing is that I want this to happen as you type. So when you type a number into an input element I want this spacing to be added on the fly.
Does anyone have a good solution for this?
I'm using this function to do this on static outputs, but it doesn't work well when getting the value from a textbox, running it through the function and then putting it back, for some reason.
function delimitNumber(number) {
var delimiter = " ";
number = new String(number);
var parts = number.split('.', 2);
var decimal = parts[1];
var i = parseInt(parts[0]);
if(isNaN(i))
return '';
var minus = '';
if (i < 0)
minus = '-';
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3) {
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if (n.length > 0)
a.unshift(n);
n = a.join(delimiter);
if (typeof decimal === 'undefined' || decimal.length < 1)
number = n;
else
number = n + '.' + decimal;
number = minus + number; // Assemble the number with negative sign (empty if positive)
return number;
}
<input type="text" id="number" />
JS:
$('#number').on("keyup", function() {
this.value = this.value.replace(/ /g,"");
this.value = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
});
http://jsfiddle.net/LLcsxr6c/
I used the keyup event because keypress or keydown will be triggered just before the input box is actually updated.
With jQuery 2 you can use $('#number').on("input", function()
Create a function that will do the string manipulation for you. Next, set up a listener on your input box to listen for a key down. That key down event should trigger your function, passing the value of your input box, and in turn setting the value to the newly spaced out string.

JavaScript - Show numbers with decimals

I'm trying to show numbers in labels. If the number > 1000 the format should look like
1.000 or 1,000
I tried with toFixed but it is not the solution, also toPrecision but it gave me a number like 1,2e+
I tried with
number/1000
but when the number ends up with a 0, it disappears from the result, so how can i do this??
I whipped up the following function. It will add a comma after 3 digits. Works on whole numbers.
function formatNumber(num)
{
var formattedNumber = "";
var numString = num.toString();
var numCount = 0;
for (var index = numString.length - 1; index >= 0; index--)
{
if (numCount % 3 == 0
&& numString[index] != '-'
&& formattedNumber)
{
formattedNumber = ',' + formattedNumber;
}
formattedNumber = numString[index] + formattedNumber;
numCount++;
}
return formattedNumber;
}
You would have to write your own function. Something like this:
http://www.mredkj.com/javascript/nfbasic.html
EDIT: Found the original code

Categories