Evaluating numbers that include thousand separators - javascript

I understand that if the parseFloat function encounters any character other than numeric characters (0-9+-. and exponents) it just evaluates the number up to that character, discarding anything else.
I'm having a problem where I need to be able to validate numbers with thousand separators like so:
var number = "10,000.01"; //passes
var numberWithoutThousand = "10000.01"; //fails
//i.e:
if(parseFloat(number) <= 10000) {
return true;
}
//passess
problem is the above code returns true when technically that number is larger than 10,000.
What's the best way to get around this? I've considered stripping out the comma before testing the number, but not sure that is a good strategy.

You don't have numbers, you have strings, so just removing the comma is the way to go
number = number.replace(/\,/g, '');

Your "stripping the comma" strategy seems good to me.
if ( parseFloat( number.replace(",","") ) ) { etc(); }

As has been suggested, to have , in the number it must be a string and so do a search and replace. If you are having to do this on a regular basis then make yourself a reusable function.
Javascript
function myParseFloat(value) {
if (typeof value === 'string') {
value = value.replace(/,/g, '');
}
return parseFloat(value);
}
var number1 = "10,000.01",
number2 = "10000.01",
number3 = 10000.01;
console.log(myParseFloat(number1), myParseFloat(number2), myParseFloat(number3));
Output
10000.01 10000.01 10000.01
On jsFiddle

Related

Counting numbers after decimal point in JavaScript

I have a problem in JavaScript. Is it possible to check how many numbers are after the decimal point? I tried to do it using a.toString().split(".")[1]), but if there is no decimal point in the number, there is an error. What should I do if I want the system to do nothing if there is no decimal point?
You're on the right track. You can also .includes('.') to test if it contains a decimal along with .length to return the length of the decimal portion.
function decimalCount (number) {
// Convert to String
const numberAsString = number.toString();
// String Contains Decimal
if (numberAsString.includes('.')) {
return numberAsString.split('.')[1].length;
}
// String Does Not Contain Decimal
return 0;
}
console.log(decimalCount(1.123456789)) // 9
console.log(decimalCount(123456789)) // 0
Convert to a string, split on “.”, then when there is no “.” to split on, assume it’s empty string '' (the part you’re missing), then get said string’s length:
function numDigitsAfterDecimal(x) {
var afterDecimalStr = x.toString().split('.')[1] || ''
return afterDecimalStr.length
}
console.log(numDigitsAfterDecimal(1.23456))
console.log(numDigitsAfterDecimal(0))
You could check if no dot is available, then return zero, otherwise return the delta of the lenght and index with an adjustment.
function getDigits(v) {
var s = v.toString(),
i = s.indexOf('.') + 1;
return i && s.length - i;
}
console.log(getDigits(0));
console.log(getDigits(0.002));
console.log(getDigits(7.654321));
console.log(getDigits(1234567890.654321));
The condition you need is:
number.split('.')[1].length
It checks if there are any numbers after the dot which separates the number from its decimal part.
I'm not sure if you are able to use split on numbers though. If not, parse it to a string.
You first need to convert the decimal number to string and then get the count of character after decimal point,
var a = 10.4578;
var str = a.toString();
if(str){
var val = str.split('.');
if(val && val.length == 2){
alert('Length of number after decimal point is ', val[1].length);
} else {
alert('Not a decimal number');
}
}
The output is 4

Show numbers to second nearest decimal

I'm very new to Javascript so please bear with me.
I have this function that adds up a total. How do I make it so that it shows the nearest two decimal places instead of no decimal places?
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".row-total-input").each(function() {
var valString = $(this).val() || 0;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
}
Thank you!
Edit: As requested: commaFormatted:
function CommaFormatted(amount) {
var delimiter = ",";
var i = parseInt(amount);
if(isNaN(i)) { return ''; }
i = Math.abs(i);
var minus = '';
if (i < 0) { minus = '-'; }
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);
amount = "$" + minus + n;
return amount;
}
Well parseInt parses integers, so you are getting rid of any decimals right there. Use parseFloat.
E.g.
parseFloat('10.599').toFixed(2); //10.60
You might also want to change your commaFormatted function to something like:
function commaFormatted(amount) {
if (!isFinite(amount) || typeof amount !== 'number') return '';
return '$' + amount.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
}
commaFormatted(0); //$0.00
commaFormatted(1.59); //$1.59
commaFormatted(999999999.99); //$999,999,999.99
Use to function toFixed(2)
The 2 is an integer parameter that says use 2 decimal points, assuming your comma formatted code does not turn it into a string. (If it does, fix the decimals BEFORE you run it through the formatting)
$("#product-subtotal").val(CommaFormatted(parseFloat(prodSubTotal).toFixed(2)));
Remember to parseFloat because the val() could be a string!`
You're looking for toFixed(). It takes one parameter, digits. The parameter is documented as follows:
The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.
Do also note that parseInt() parses integers, truncating any decimals you might have. parseFloat() will preserve decimals as expected.
I solved my problem. I simply changed:
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
to
$("#product-subtotal").val(prodSubTotal);
As I stated in the comments, this was not a script I wrote. It is a script Chris Coyier wrote and I was just trying to amend it. I guess I didn't need to use CommaFormatted for my purposes?
Thank you all for your help!

Integer Comparison

I need to compare two Integers which could exceed Integer range limit. How do I get this in javascript.
Initially, I get the value as String, do a parseInt and compare them.
var test = document.getElementById("test").value;
var actual = document.getElementById("actual").value;
if ( parseInt(test) == parseInt(actual)){
return false;
}
Any options to use long ? Also, which is best to use parseInt or valueOf ??
Any suggestions appreciated,
Thanks
You'd better to assign the radix. Ex. parseInt('08') will give 0 not 8.
if (parseInt(test, 10) === parseInt(actual, 10)) {
Leave them in String and compare (after you have cleaned up the string of leading and trailing spaces, and other characters that you consider safe to remove without changing the meaning of the number).
The numbers in Javascript can go up to 53-bit precision. Check whether your number is within range.
Since the input is expected to be integer, you can be strict and only allow the input to only match the regex:
/\s*0*([1-9]\d*|0)\s*/
(Arbitrary leading spaces, arbitrary number of leading 0's, sequence of meaningful digits or single 0, arbitrary trailing spaces)
The number can be extract from the first capturing group.
Assuming integers and that you've already validated for non-numeric characters that you don't want to be part of the comparison, you can clean up some leading/trailing stuff and then just compare lengths and if lengths are equal, then do a plain ascii comparison and this will work for any arbitrary length of number:
function mTrim(val) {
var temp = val.replace(/^[\s0]+/, "").replace(/\s+$/, "");
if (!temp) {
temp = "0";
}
return(temp);
}
var test = mTrim(document.getElementById("test").value);
var actual = mTrim(document.getElementById("actual").value);
if (test.length > actual.length) {
// test is greater than actual
} else if (test.length < actual.length) {
// test is less than actual
} else {
// do a plain ascii comparison of test and actual
if (test == actual) {
// values are the same
} else if (test > ascii) {
// test is greater than actual
} else {
// test is less than actual
}
}

check if number string contains decimal?

After doing a sqrt()
How can I be check to see if the result contains only whole numbers or not?
I was thinking Regex to check for a decimal - if it contains a decimal, that means it didn't root evenly into whole numbers. Which would be enough info for me.
but this code isnt working...
result = sqrt(stringContainingANumber);
decimal = new RegExp(".");
document.write(decimal.test(result));
I bet there's other ways to accomplish the same thing though.
. means any char.
You have to quote the dot. "\."
Or you could test
if (result > Math.floor(result)) {
// not an decimal
}
You can use the % operator:
result % 1 === 0; // rest after dividing by 1 should be 0 for whole numbers
Use indexOf():
​var myStr = "1.0";
myStr.indexOf("."); // Returns 1
// Other examples
myStr.indexOf("1"); // Returns 0 (meaning that "1" may be found at index 0)
myStr.indexOf("2"); // Returns -1 (meaning can't be found)
"." has meaning in the regex syntax which is "anything" you need to escape it using "\."
If its a string we can just use split function and then check the length of the array returned. If its more than 1 it has decimal point else not :). This doesn't work for numbers though :(. Please see the last edit. It works for string as well now :)
function checkDecimal() {
var str = "202.0";
var res = str.split(".");
alert(res.length >1);
var str1 = "20";
alert(str1.split(".").length>1);
}
Hope it helps someone.
Happy Learning :)
Are you looking for checking string containing decimal digits ,
you can try like this
var num = "123.677";
if (!isNaN(Number(num)) {
alert("decimal no");
}
else {
alert("Not a decimal number");
}
I am sorry. This answer is too late. but I hope this will help.
function isThisDecimal(val){
if (!(val.indexOf(".") == -1)){
return true; // decimal
}
return false; // number
}
console.log(isThisDecimal("12.00")); //true
console.log(isThisDecimal("12.12")); //true
console.log(isThisDecimal("12"));// false

Convert String with Dot or Comma as decimal separator to number in JavaScript

An input element contains numbers a where comma or dot is used as decimal separator and space may be used to group thousands like this:
'1,2'
'110 000,23'
'100 1.23'
How would one convert them to a float number in the browser using JavaScript?
jQuery and jQuery UI are used. Number(string) returns NaN and parseFloat() stops on first space or comma.
Do a replace first:
parseFloat(str.replace(',','.').replace(' ',''))
I realise I'm late to the party, but I wanted a solution for this that properly handled digit grouping as well as different decimal separators for currencies. As none of these fully covered my use case I wrote my own solution which may be useful to others:
function parsePotentiallyGroupedFloat(stringValue) {
stringValue = stringValue.trim();
var result = stringValue.replace(/[^0-9]/g, '');
if (/[,\.]\d{2}$/.test(stringValue)) {
result = result.replace(/(\d{2})$/, '.$1');
}
return parseFloat(result);
}
This should strip out any non-digits and then check whether there was a decimal point (or comma) followed by two digits and insert the decimal point if needed.
It's worth noting that I aimed this specifically for currency and as such it assumes either no decimal places or exactly two. It's pretty hard to be sure about whether the first potential decimal point encountered is a decimal point or a digit grouping character (e.g., 1.542 could be 1542) unless you know the specifics of the current locale, but it should be easy enough to tailor this to your specific use case by changing \d{2}$ to something that will appropriately match what you expect to be after the decimal point.
The perfect solution
accounting.js is a tiny JavaScript library for number, money and currency formatting.
Check this for ref
You could replace all spaces by an empty string, all comas by dots and then parse it.
var str = "110 000,23";
var num = parseFloat(str.replace(/\s/g, "").replace(",", "."));
console.log(num);
I used a regex in the first one to be able to match all spaces, not just the first one.
This is the best solution
http://numeraljs.com/
numeral().unformat('0.02'); = 0.02
What about:
parseFloat(str.replace(' ', '').replace('.', '').replace(',', '.'));
All the other solutions require you to know the format in advance. I needed to detect(!) the format in every case and this is what I end up with.
function detectFloat(source) {
let float = accounting.unformat(source);
let posComma = source.indexOf(',');
if (posComma > -1) {
let posDot = source.indexOf('.');
if (posDot > -1 && posComma > posDot) {
let germanFloat = accounting.unformat(source, ',');
if (Math.abs(germanFloat) > Math.abs(float)) {
float = germanFloat;
}
} else {
// source = source.replace(/,/g, '.');
float = accounting.unformat(source, ',');
}
}
return float;
}
This was tested with the following cases:
const cases = {
"0": 0,
"10.12": 10.12,
"222.20": 222.20,
"-222.20": -222.20,
"+222,20": 222.20,
"-222,20": -222.20,
"-2.222,20": -2222.20,
"-11.111,20": -11111.20,
};
Suggestions welcome.
Here's a self-sufficient JS function that solves this (and other) problems for most European/US locales (primarily between US/German/Swedish number chunking and formatting ... as in the OP). I think it's an improvement on (and inspired by) Slawa's solution, and has no dependencies.
function realParseFloat(s)
{
s = s.replace(/[^\d,.-]/g, ''); // strip everything except numbers, dots, commas and negative sign
if (navigator.language.substring(0, 2) !== "de" && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(s)) // if not in German locale and matches #,###.######
{
s = s.replace(/,/g, ''); // strip out commas
return parseFloat(s); // convert to number
}
else if (/^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(s)) // either in German locale or not match #,###.###### and now matches #.###,########
{
s = s.replace(/\./g, ''); // strip out dots
s = s.replace(/,/g, '.'); // replace comma with dot
return parseFloat(s);
}
else // try #,###.###### anyway
{
s = s.replace(/,/g, ''); // strip out commas
return parseFloat(s); // convert to number
}
}
Here is my solution that doesn't have any dependencies:
return value
.replace(/[^\d\-.,]/g, "") // Basic sanitization. Allows '-' for negative numbers
.replace(/,/g, ".") // Change all commas to periods
.replace(/\.(?=.*\.)/g, ""); // Remove all periods except the last one
(I left out the conversion to a number - that's probably just a parseFloat call if you don't care about JavaScript's precision problems with floats.)
The code assumes that:
Only commas and periods are used as decimal separators. (I'm not sure if locales exist that use other ones.)
The decimal part of the string does not use any separators.
try this...
var withComma = "23,3";
var withFloat = "23.3";
var compareValue = function(str){
var fixed = parseFloat(str.replace(',','.'))
if(fixed > 0){
console.log(true)
}else{
console.log(false);
}
}
compareValue(withComma);
compareValue(withFloat);
This answer accepts some edge cases that others don't:
Only thousand separator: 1.000.000 => 1000000
Exponentials: 1.000e3 => 1000e3 (1 million)
Run the code snippet to see all the test suite.
const REGEX_UNWANTED_CHARACTERS = /[^\d\-.,]/g
const REGEX_DASHES_EXEPT_BEGINNING = /(?!^)-/g
const REGEX_PERIODS_EXEPT_LAST = /\.(?=.*\.)/g
export function formatNumber(number) {
// Handle exponentials
if ((number.match(/e/g) ?? []).length === 1) {
const numberParts = number.split('e')
return `${formatNumber(numberParts[0])}e${formatNumber(numberParts[1])}`
}
const sanitizedNumber = number
.replace(REGEX_UNWANTED_CHARACTERS, '')
.replace(REGEX_DASHES_EXEPT_BEGINING, '')
// Handle only thousands separator
if (
((sanitizedNumber.match(/,/g) ?? []).length >= 2 && !sanitizedNumber.includes('.')) ||
((sanitizedNumber.match(/\./g) ?? []).length >= 2 && !sanitizedNumber.includes(','))
) {
return sanitizedNumber.replace(/[.,]/g, '')
}
return sanitizedNumber.replace(/,/g, '.').replace(REGEX_PERIODS_EXEPT_LAST, '')
}
function formatNumberToNumber(number) {
return Number(formatNumber(number))
}
const REGEX_UNWANTED_CHARACTERS = /[^\d\-.,]/g
const REGEX_DASHES_EXEPT_BEGINING = /(?!^)-/g
const REGEX_PERIODS_EXEPT_LAST = /\.(?=.*\.)/g
function formatNumber(number) {
if ((number.match(/e/g) ?? []).length === 1) {
const numberParts = number.split('e')
return `${formatNumber(numberParts[0])}e${formatNumber(numberParts[1])}`
}
const sanitizedNumber = number
.replace(REGEX_UNWANTED_CHARACTERS, '')
.replace(REGEX_DASHES_EXEPT_BEGINING, '')
if (
((sanitizedNumber.match(/,/g) ?? []).length >= 2 && !sanitizedNumber.includes('.')) ||
((sanitizedNumber.match(/\./g) ?? []).length >= 2 && !sanitizedNumber.includes(','))
) {
return sanitizedNumber.replace(/[.,]/g, '')
}
return sanitizedNumber.replace(/,/g, '.').replace(REGEX_PERIODS_EXEPT_LAST, '')
}
const testCases = [
'1',
'1.',
'1,',
'1.5',
'1,5',
'1,000.5',
'1.000,5',
'1,000,000.5',
'1.000.000,5',
'1,000,000',
'1.000.000',
'-1',
'-1.',
'-1,',
'-1.5',
'-1,5',
'-1,000.5',
'-1.000,5',
'-1,000,000.5',
'-1.000.000,5',
'-1,000,000',
'-1.000.000',
'1e3',
'1e-3',
'1e',
'-1e',
'1.000e3',
'1,000e-3',
'1.000,5e3',
'1,000.5e-3',
'1.000,5e1.000,5',
'1,000.5e-1,000.5',
'',
'a',
'a1',
'a-1',
'1a',
'-1a',
'1a1',
'1a-1',
'1-',
'-',
'1-1'
]
document.getElementById('tbody').innerHTML = testCases.reduce((total, input) => {
return `${total}<tr><td>${input}</td><td>${formatNumber(input)}</td></tr>`
}, '')
<table>
<thead><tr><th>Input</th><th>Output</th></tr></thead>
<tbody id="tbody"></tbody>
</table>
From number to currency string is easy through Number.prototype.toLocaleString. However the reverse seems to be a common problem. The thousands separator and decimal point may not be obtained in the JS standard.
In this particular question the thousands separator is a white space " " but in many cases it can be a period "." and decimal point can be a comma ",". Such as in 1 000 000,00 or 1.000.000,00. Then this is how i convert it into a proper floating point number.
var price = "1 000.000,99",
value = +price.replace(/(\.|\s)|(\,)/g,(m,p1,p2) => p1 ? "" : ".");
console.log(value);
So the replacer callback takes "1.000.000,00" and converts it into "1000000.00". After that + in the front of the resulting string coerces it into a number.
This function is actually quite handy. For instance if you replace the p1 = "" part with p1 = "," in the callback function, an input of 1.000.000,00 would result 1,000,000.00

Categories

Resources