How to round a number up and add numeric punctuation - javascript

I've got the following pen: http://codepen.io/anon/pen/LVLzvR
I cant quite figure out how to round the number up so you don't break the punctuation. I need to round the number up as I don't want to see a value like 33,333.,333
//ADDS PUNCTUATION EVERY THREE CHARACTERS
$('input.numericpunctuation').keyup(function(event){
var oNum= $(this).val(); // USE THIS NUMBER FOR CALCULATION
var num = oNum.replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
console.log(num2);
console.log(oNum);
// the following line has been simplified. Revision history contains original.
$(this).val(num2);
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
Example input event:
If I input 5555, is expect to see (and do see) 5,555. However if I add 5555.55 I get 5,555,.55. Ideally id like to round the number up removing the decimal.

The problem isn't just with decimals, you will get the wrong formatting also by entering non digits, e.g., clicking King Kong will result in Kin,g K,ong. So, what you probably want is to filter out non-digits, which can be done by changing the line var oNum= $(this).val(); to:
var oNum= $(this).val().match(/\d/g).join('');
The value inside the match function is a RegEx object - if you never used it before then congratulations!

Related

Calculation for comma number gives NaN value

I tried to multiply 2 input where user need to key in the number but the output gives me NaN value.
The input number btw have comma separator. I tried to implement the method from the link below and the comma separator is working. It just that when I multiply them it gives me NaN value.
Can jQuery add commas while user typing numbers?
Can anybody help me with this. Really appreciate your help.
Javascript
$('.textInput').on('change keyup', function() {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/(\d)(?=(\d{3})+$)/g, '$1,');
;
});
product_total_price=0;
var product_price= Number($('#id_Product-0-price').val());
var product_quantity= Number($('#id_Product-0-quantity').val());
product_total_price= product_price * product_quantity;
$('#id_Product-0-total_price').val(product_total_price);
});
The problem here is that you have modified your inputs to show commas, which is totally fine, BUT you didn't remove the commas before casting/converting them to Number.
A quick test of converting a Number from string "1,234" will give you a NaN result. See screenshot:
Solution:
Remove Comma
Then cast to Number
Then compute product_total_price
To remove all commas, simpy use:
yourString.replace(/,/g, '')
Hope this helps!

Regular expression for decimals

Hi Experts,
I have a requirement where I think regular expressions might help reducing a lot of if statements and conditions in my code.
My requirement is something like this
I have a quantity field that is displayed in the UI( JavaScript) which has a control factor (based on the quantity field's Unit of Measurement) send from the backend .
Example my Quantity = "126.768"
The control factor D = "2" (which means the number of display positions after the decimal point is 2) .
Now I need a regex to find the following
Regex1 should check whether the quantity is having any decimal points at all. If so then it should check whether the value after decimal points are not just zeros (ex sometimes quantity comes without getting formatted with the full length of decimal points 145.000, which in our case should be displayed as 145 in the UI and the control factor D doesn't need to be considered). Also RegEx should consider quantity values like ".590" ".001" etc.
Since I am new to RegEx I am struggling to come up with an expression
I managed to make a very basic RegEx that just check for the "." within the quantity and all the values after the "."
RegEx = /[.]\d*/g
If RegEx1 returns a positive result . Then Regex2 should now check for the value D. It should adjust the decimal points based on D. For example if D = 3 and quantity = 345.26 then the output of regex2 should give 345.260 and similarly is D = 1 then quantity should be 345.3 ( donno whether rounding is possible using RegEx, a solution without rounding is also fine).
Regards,
Bince
The first regex is
"\d*\.\d*[1-9]\d*"
It searches for at least 1 non-zero digit after the dot.
For the second point, you can round with regex only if the digits overcomes the control factor, while for the 0-padding you can't use regex:
function round(num, control) {
var intPart = num.split(".")[0];
var decPart = num.split(".")[1];
decPart = decPart.substring(0, control); //this does the truncation
var padding = "0".repeat(control - decPart.length); //this does the 0-padding
return intPart + "." + decPart + padding;
}
var num1 = "210.012";
var num2 = "210.1";
var control = 2;
console.log(round(num1, control));
console.log(round(num2, control));
You shouldn't need for any check or regex,
there is a Number.prototype.toFixed method that will help you to adjust decimals.
It basically rounds a number to the nearest decimal point and returns a string. If you're working with strings, make sure you cast it before (using Number statically)
console.log(17.1234.toFixed(2)); // round it down
console.log(17.1264.toFixed(2)); // round it up
console.log(17..toFixed(2)); // Integer
console.log(Number("126.768").toFixed(2)); // from string casting

JavaScript: Retrieve negative floating point number from string of mutiple sums

I have a simple app that allows me to caculate the total amount invoiced and deposited in a route. However I want to allow the user to input multiple values in a single input field; e.g:
500+50+36.5-45.2-10.
I have written a function that will retrieve this input and then split this string into elements of an array at the + sign and immediately parse the values to numbers and then add them and return the total the user inputs into each individual field. This is all well as long as the user does no use any sign other than +.
I have searched the use of regexp:
regular expression in javascript for negative floating point number result stored in array
Javascript Regular expression to allow negative double value?
but none of the results seem to work.
How could I make my code retrieve the values so that the negative values get passed into the array as negative values?
Here is a snippet of my Js code:
For the full code, visit my fiddle.
totalInvoiced: function () {
var a = A.invoiced.value;
var value1Arr = [];
value1Arr = a.split("+").map(parseFloat);
var value1 = 0;
value1Arr.forEach(function (value) {
value1 += value;
});
I really like PhistucK's solution, but here an alternative with regex:
value1Arr = a.split(/(?=\+|\-)/);
This will split it, but keeps the delimiter, so the result will be:
["500", "+50", "+36.5", "-45.2", "-10"]
A bit dirty, but maybe a.replace(/-/g, "+-").split("+"), this way, you add a plus before every minus, since the negative numbers just basically lack an operator.
You can use this pattern that splits on + sign or before - sign:
var str = '500+50+36.5-45.2-10';
console.log(str.split(/\+|(?=-)/));

Javascript convert string to integer

I am just dipping my toe into the confusing world of javascript, more out of necessity than desire and I have come across a problem of adding two integers.
1,700.00 + 500.00
returns 1,700.00500.00
So after some research I see that 1,700.00 is being treated as a string and that I need to convert it.
The most relevant pages I read to resolve this were this question and this page. However when I use
parseInt(string, radix)
it returns 1. Am I using the wrong function or the an incorrect radix (being honest I can't get my head around how I decide which radix to use).
var a="1,700.00";
var b=500.00;
parseInt(a, 10);
Basic Answer
The reason parseInt is not working is because of the comma. You could remove the comma using a regex such as:
var num = '1,700.00';
num = num.replace(/\,/g,'');
This will return a string with a number in it. Now you can parseInt. If you do not choose a radix it will default to 10 which was the correct value to use here.
num = parseInt(num);
Do this for each of your string numbers before adding them and everything should work.
More information
How the replace works:
More information on replace at mdn:
`/` - start
`\,` - escaped comma
`/` - end
`g` - search globally
The global search will look for all matches (it would stop after the first match without this)
'' replace the matched sections with an empty string, essentially deleting them.
Regular Expressions
A great tool to test regular expressions: Rubular and more info about them at mdn
If you are looking for a good tutorial here is one.
ParseInt and Rounding, parseFloat
parseInt always rounds to the nearest integer. If you need decimal places there are a couple of tricks you can use. Here is my favorite:
2 places: `num = parseInt(num * 100) / 100;`
3 places: `num = parseInt(num * 1000) / 1000;`
For more information on parseInt look at mdn.
parseFloat could also be used if you do not want rounding. I assumed you did as the title was convert to an integer. A good example of this was written by #fr0zenFry below. He pointed out that parseFloat also does not take a radix so it is always in base10. For more info see mdn.
Try using replace() to replace a , with nothing and then parseFloat() to get the number as float. From the variables in OP, it appears that there may be fractional numbers too, so, parseInt() may not work well in such cases(digits after decimal will be stripped off).
Use regex inside replace() to get rid of each appearance of ,.
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = a+b;
This should give you correct result even if your number is fractional like 1,700.55.
If I go by the title of your question, you need an integer. For this you can use parseInt(string, radix). It works without a radix but it is always a good idea to specify this because you never know how browsers may behave(for example, see comment #Royi Namir). This function will round off the string to nearest integer value.
var a = parseInt('1,700.00'.replace(/,/g, ''), 10); //radix 10 will return base10 value
var b = parseInt('500.00'.replace(/,/g, ''), 10);
var sum = a+b;
Note that a radix is not required in parseFloat(), it will always return a decimal/base10 value. Also, it will it will strip off any extra zeroes at the end after decimal point(ex: 17500.50 becomes 17500.5 and 17500.00 becomes 17500). If you need to get 2 decimal places always, append another function toFixed(decimal places).
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = (a+b).toFixed(2); //change argument in toFixed() as you need
// 2200.00
Another alternative to this was given by #EpiphanyMachine which will need you to multiply and then later divide every value by 100. This may become a problem if you want to change decimal places in future, you will have to change multiplication/division factor for every variable. With toFixed(), you just change the argument. But remember that toFixed() changes the number back to string unlike #EpiphanyMachine solution. So you will be your own judge.
try this :
parseFloat(a.replace(/,/g, ''));
it will work also on : 1,800,300.33
Example :
parseFloat('1,700,800.010'.replace(/,/g, '')) //1700800.01
Javascript doesn't understand that comma. Remove it like this:
a.replace(',', '')
Once you've gotten rid of the comma, the string should be parsed with no problem.

Javascript Regex for Decimal Numbers - Replace non-digits and more than one decimal point

I am trying to limit an input to a decimal number. I'd like any invalid characters not to be displayed at all (not displayed and then removed). I already have this implemented but for whole integers (like input for a phone number) but now I need to apply it for decimal input.
Sample input/output:
default value 25.00 -> type 2b5.00 -> display 25.00
default value 265.50 -> type 2.65.50 -> display 265.50 (as if prevented decimal point from being entered)
default value 265.52 -> type 265.52. -> display 265.52 (same as previous one)
End New Edit
I found many threads that dealt with "decimal input" issue but almost 99% of them deal only with "match"ing and "test"ing the input while my need is to replace the invalid characters.
Other than trying many regexes like /^\d+(\.\d{0,2})?$/, I also tried something like the below which keeps only the first occurrence in the input. This still isn't my requirement because I need the "original" decimal point to remain not the first one in the new input. This was the code for it:
[this.value.slice(0, decimalpoint), '.', this.value.slice(decimalpoint)].join('')
This thread is the closest to what I need but since there was no response to the last comment about preventing multiple decimal points (which is my requirement), it wasn't useful.
Any help would be appreciated.
Outline: find the first ., split there and clean the parts, else just return cleaned value.
function clean(string) {
return string.replace(/[^0-9]/g, "");
}
var value = "a10.10.0";
var pos = value.indexOf(".");
var result;
if (pos !== -1) {
var part1 = value.substr(0, pos);
var part2 = value.substr(pos + 1);
result = clean(part1) + "." + clean(part2);
} else {
result = clean(value);
}
console.log(result); // "10.100"

Categories

Resources