How to round of prices with comma's instead of dots? - javascript

In The Netherlands we use comma's in numbers where in other countries dots would be used. For example we use 39,99 and in other countries 39.99.
In a feed with prices we would have prices with such comma use, but I'm having trouble using those as numbers and rounding them by two digits behind the comma (or behind the dot really).
var num1 = "39,1234";
var num = parseInt(num1);
var n = num.toFixed(2);
console.log(n);
Here is such a number. I would like it to result in 39,12. They way I was thinking is then first use it as a string. Then turn that string into a number and use toFixed to round it of to two digets. But it results in 39,00 instead of 39,12.
Perhaps I'm thinking wrong and I should use some other way to make 39,1234 to be seen as 39.1234 so that it is rounded correctly as a number?
How can I used 39,1234 as a number 39,1234 instead of a string? So that I wouldn't have to go through a feed and replace commas by dots first in all my prices?

Edit: Regex version
Earlier I didn't realize that OP originally wanted it back to the format "xx,xx". This is a more elegant solution:
var num1 = "39,1234";
let n = num1.replace(/(?<=,\d{2})(\d*)$/,"");
console.log(n); //32,12
Regex explanation:
(?<=,\d){2} begins a lookbehind match for , followed by digits \d, 2 of them {2}. Lookbehind matches are not replaced.
(\d*)$ when we've found the lookbehind pattern, we match more digits \d, all * of them, till we reach end of string $. This is the match that will get replaced.
Original Solution
What you want is:
var num1 = "39,1234";
var n = parseFloat(num1.replace(",",".")).toFixed(2);
console.log(n); //39.12
// replaces it back to ",", but now it's a string!
n = n.replace(".",",")
console.log(n); //39,12
Explanation:
First replace "," with "." with replace()
Convert to float (not integer) with parseFloat()
Set to 2 decimal places with .toFixed(2)
Replace "." with ",". But now it's a string!
Note: this will not work if the currency value contains . as a thousandth separator. e.g. "40.200,1576". If that's the case, add another line num1 = num1.replace(".","") to strip out the separator before passing it to the parseFloat(...) line.

Try this
comdecimal= num1.replace(".","")
alert(comdecimal);
dotdecimal= comdecimal.replace(",",".")
alert(dotdecimal);
dotdecimal = Math.round(dotdecimal* 100) / 100;
alert(dotdecimal);

Since you're working with currency, I'd recommend using JS ES6 designated NumberFormat feature. Your code should look like this and be easily reused:
const formatter = new Intl.NumberFormat('nl-NL', {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 2
});
console.log(formatter.format('145,53'.replace(',','.')));
//"€ 145,53"

Related

Replace the numbers with *

How to replace the last two digits with asterisks using JavaScript
Example: console.log(Math.random()) // 0.6334249899746089 || 0.63342498997460**
I gave you as an example random
To replace the last 2 digits with some characters, firstly convert it to a string and then, using the slice() method, append the characters. You can read more about the slice() method in its MDN Documentation.
let numberAsString = Math.random().toString(); //your number as a string
let result = numberAsString.slice(0, -2) + '**'; //cut and append your asterisks

Javascript timestamp formatting with regular expression?

how do i format a string of 2014-09-10 10:07:02 into something like this:
2014,09,10,10,07,02
Thanks!
Nice and simple.
var str = "2014-09-10 10:07:02";
var newstr = str.replace(/[ :-]/g, ',');
console.log(newstr);
Based on the assumption that you want to get rid of everything but the digits, an alternative is to inverse the regex to exclude everything but digits. This is, in effect, a white-listing approach as compared to the previously posted black-listing approach.
var dateTimeString = "2016-11-23 02:00:00";
var regex = /[^0-9]+/g; // Alternatively (credit zerkms): /\D+/g
var reformattedDateTimeString = dateTimeString.replace(regex, ',');
Note the + which has the effect of replacing groups of characters (e.g. two spaces would be replaced by only a single comma).
Also note that if you intend to use the strings as digits (e.g. via parseInt), numbers with a leading zero are interpreted within JavaScript as being base-8.

Check for numeric value with optional commas javascript

I need to check a value if it is numeric and optionally contains commas.
I tried
var input=3433;
var pattern=/^[1-9]\d{0,2}(\.\d{3})*(,\d+)?$/;
pattern.test(input);
but it always gave me false;
I don't want to use $.isNumeric as it does not check for commas.
Assuming you're using the comma as a thousands separator, the easiest way to do this is to just remove the commas when converting:
var num = +str.replace(/,/g, '');
if (!isNaN(num)) {
// It's a valid number
}
If your locale uses . as the thousands separator and , as a decimal point (as your regex seems to suggest), since JavaScript always uses them the other way around, we have more to change in the string first:
var num = +str.replace(/\./g, '').replace(/,/g, ".");
if (!isNaN(num)) {
// It's a valid number
}
I must process in different ways strings and string-numbers.
So I must test if a string is a string-number (not a valid number), using the locale convention.
My rude solution is:
var num = +str.replace(/\./g, '').replace(/,/g, '');
if (!isNaN(num))...
This works with USA, EUR locales. The control about 'valid number' is done after, car I wanna send detailed WARNING/ERROR messages to user.
Your sample var input is not matched by your regex because of the dot.
You could do:
var input=3433;
var pattern=/^[1-9]\d{0,2}(\.?\d{3})*(,\d+)?$/;
// the dot is optional __^
pattern.test(input);
This regex will match:
123
1234
1.234
123,45
1234,567
1.234,56
1.234.567,89

Javascript numeric input (regex) validation rules

I'm a bit stuck here.
With regards to the input of accounting data, the analyst requested a specific set of rules on the input of decimal data in text boxes.
Since I have not studied regular expressions at this point, and because I have very strict deadlines to attend with each a lot of work, I request your help.
The rules are (on blur):
IE8+ compatible;
Set default at 2 digits behind the comma;
Disallow other characters than ".", "," and numeric characters;
If there are multiple separators in the returned number, only keep the last one.
Explanation:
Employees may have different regional settings, and comma / dot may be used as either decimal or thousands separator.
In case an employee copy - pastes both the thousand and the decimal separator, it has to be ignored.
What I've done so far, but doesn't fulfill the requirements:
http://jsfiddle.net/NxFHL/1/
$('#test_rules.numeric').on('blur', function(){
var myString = $('#test_rules.numeric').val();
myString = parseFloat(myString.replace(/[^\d.-]/g, ''));
myString = toFixed(myString, 2);
console.log(myString);
});
function toFixed(value, precision) {
var power = Math.pow(10, precision || 0);
return
String(Math.round(value * power) / power);
}
The regular expression used doesn't work correctly as it only accepts dot, not comma.
Also I am not sure about how I should make it so that only the last separator stays (so that the thousands separator gets ignored).
Try this function:
function parseInputNum(val) {
var sep = val.lastIndexOf('.') > val.lastIndexOf(',')? '.' : ',';
var arr = val.replace(new RegExp('[^\\d'+sep+']+', 'g'), '')
.match(new RegExp('(\\d+(?:['+sep+']\\d+|))$'));
return arr? arr[1].replace(/[,]/g, '.') : false;
}
You can use this pattern:
^(?:[1-9](?:[0-9]{0,2}(?:([.,])[0-9]{3})?(?:\1[0-9]{3})*|[0-9]*)|0)(?!\1)[.,][0-9]{2}$
This pattern will check numbers like:
123,45
12,45
0.45
123,456,789.12
1234.56
123.456.789,12
but not numbers like:
12.23.45,12
012,345,678,91
1234,567.89
123,456,78
To convert the string into a number you must remove the thousand delimiter before. This can easily be done since the delimiter (if present) is in the capturing group 1. You must probably too replace the , by the . if it is used as decimal separator.

Using JavaScript's parseInt at end of string

I know that
parseInt(myString, 10) // "Never forget the radix"
will return a number if the first characters in the string are numerical, but how can I do this in JavaScript if I have a string like "column5" and want to increment it to the next one ("column6")?
The number of digits at the end of the string is variable.
parseInt("column5".slice(-1), 10);
You can use -1 or -2 for one to two digit numbers, respectively.
If you want to specify any length, you can use the following to return the digits:
parseInt("column6445".match(/(\d+)$/)[0], 10);
The above will work for any length of numbers, as long as the string ends with one or more numbers
Split the number from the text, parse it, increment it, and then re-concatenate it. If the preceding string is well-known, e.g., "column", you can do something like this:
var precedingString = myString.substr(0, 6); // 6 is length of "column"
var numericString = myString.substr(7);
var number = parseInt(numericString);
number++;
return precedingString + number;
Try this:
var match = myString.match(/^([a-zA-Z]+)([0-9]+)$/);
if ( match ) {
return match[1] + (parseInt(match[2]) + 1, 10);
}
this will convert strings like text10 to text11, TxT1 to Txt2, etc. Works with long numbers at the end.
Added the radix to the parseInt call since the default parseInt value is too magic to be trusted.
See here for details:
http://www.w3schools.com/jsref/jsref_parseInt.asp
basically it will convert something like text010 to text9 which is not good ;).
var my_car="Ferrari";
var the_length=my_car.length;
var last_char=my_car.charAt(the_length-1);
alert('The last character is '+last_char+'.');
Credit to http://www.pageresource.com/jscript/jstring1.htm
Then just increment last_char
Split the word and number using RegEx.
using parseInt() increment the number.
Append to the word.
Just try to read string char by char, checking its ASCII code. If its from 48 to 57 you got your number. Try with charCodeAt function. Then just split string, increment the number and its done.

Categories