javascript not recognizing 1 var >= another - javascript

so, my problem here is that my code seems to be recognizing that 100 is < 2000, but its not recognizing that 200 < 1000
heres my code (i also use jquery as a framework FYI)
$('.filter-price').submit(function(e) {
var alert_message = '';
var price_from = $('.filter-price #price_from').val();
var price_to = $('.filter-price #price_to').val();
if (isNaN(price_from))
{
alert_message += "Price from must be a number, i.e. 500\n";
$('.filter-price #price_from').val('From');
}
if (isNaN(price_to))
{
alert_message += "Price to must be a number, i.e. 500\n";
$('.filter-price #price_to').val('To');
}
if (!isNaN(price_from) && !isNaN(price_to) && (price_from >= price_to))
{
alert_message += "Price from must be less than price to\n";
$('.filter-price #price_from').val('From');
$('.filter-price #price_to').val('To');
}
if (alert_message != '')
{
e.preventDefault();
alert(alert_message);
}
});
i've tried using parseInt() on the vars which fixes nothing.

Sorry, but you really need to do this way:
var price_from = parseInt($('.filter-price #price_from').val(), 10);
var price_to = parseInt($('.filter-price #price_to').val(), 10);
Look the result on chrome console:
'200' >= '1000'
true
200 >= 1000
false
And if you don't want to limit the numbers to int, replace parseInt(val, 10) to parseFloat(val)

parseInt works for me. Not sure what was incorrect for you.
http://jsfiddle.net/98Bzn/1
var price_from = parseInt($('.filter-price #price_from').val());
var price_to = parseInt($('.filter-price #price_to').val());

Where have you tried using parseInt()? It seems to me that it's interpreting your values as strings rather than numbers, so you need to coerce them into the correct data type.
I would do this:
function convertCurrencyToNumber(value) {
return Number(value.replace(/[^0-9\.]+/g,""));
}
...
var price_from = convertCurrencyToNumber($('.filter-price #price_from').val());
var price_to = convertCurrencyToNumber($('.filter-price #price_to').val());
It appears you're using currency, so the above will convert to a decimal for database storage or whatever else you're doing.

Related

NaN (not a number) when attempting output 2 decimal place for money value [duplicate]

I have a text box that will have a currency string in it that I then need to convert that string to a double to perform some operations on it.
"$1,100.00" → 1100.00
This needs to occur all client side. I have no choice but to leave the currency string as a currency string as input but need to cast/convert it to a double to allow some mathematical operations.
Remove all non dot / digits:
var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9.-]+/g,""));
accounting.js is the way to go. I used it at a project and had very good experience using it.
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
accounting.unformat("€ 1.000.000,00", ","); // 1000000
You can find it at GitHub
Use a regex to remove the formating (dollar and comma), and use parseFloat to convert the string to a floating point number.`
var currency = "$1,100.00";
currency.replace(/[$,]+/g,"");
var result = parseFloat(currency) + .05;
I know this is an old question but wanted to give an additional option.
The jQuery Globalize gives the ability to parse a culture specific format to a float.
https://github.com/jquery/globalize
Given a string "$13,042.00", and Globalize set to en-US:
Globalize.culture("en-US");
You can parse the float value out like so:
var result = Globalize.parseFloat(Globalize.format("$13,042.00", "c"));
This will give you:
13042.00
And allows you to work with other cultures.
I know this is an old question, but CMS's answer seems to have one tiny little flaw: it only works if currency format uses "." as decimal separator.
For example, if you need to work with russian rubles, the string will look like this:
"1 000,00 rub."
My solution is far less elegant than CMS's, but it should do the trick.
var currency = "1 000,00 rub."; //it works for US-style currency strings as well
var cur_re = /\D*(\d+|\d.*?\d)(?:\D+(\d{2}))?\D*$/;
var parts = cur_re.exec(currency);
var number = parseFloat(parts[1].replace(/\D/,'')+'.'+(parts[2]?parts[2]:'00'));
console.log(number.toFixed(2));
Assumptions:
currency value uses decimal notation
there are no digits in the string that are not a part of the currency value
currency value contains either 0 or 2 digits in its fractional part *
The regexp can even handle something like "1,999 dollars and 99 cents", though it isn't an intended feature and it should not be relied upon.
Hope this will help someone.
This example run ok
var currency = "$1,123,456.00";
var number = Number(currency.replace(/[^0-9\.]+/g,""));
console.log(number);
For anyone looking for a solution in 2021 you can use Currency.js.
After much research this was the most reliable method I found for production, I didn't have any issues so far. In addition it's very active on Github.
currency(123); // 123.00
currency(1.23); // 1.23
currency("1.23") // 1.23
currency("$12.30") // 12.30
var value = currency("123.45");
currency(value); // 123.45
typescript
import currency from "currency.js";
currency("$12.30").value; // 12.30
This is my function. Works with all currencies..
function toFloat(num) {
dotPos = num.indexOf('.');
commaPos = num.indexOf(',');
if (dotPos < 0)
dotPos = 0;
if (commaPos < 0)
commaPos = 0;
if ((dotPos > commaPos) && dotPos)
sep = dotPos;
else {
if ((commaPos > dotPos) && commaPos)
sep = commaPos;
else
sep = false;
}
if (sep == false)
return parseFloat(num.replace(/[^\d]/g, ""));
return parseFloat(
num.substr(0, sep).replace(/[^\d]/g, "") + '.' +
num.substr(sep+1, num.length).replace(/[^0-9]/, "")
);
}
Usage : toFloat("$1,100.00") or toFloat("1,100.00$")
// "10.000.500,61 TL" price_to_number => 10000500.61
// "10000500.62" number_to_price => 10.000.500,62
JS FIDDLE: https://jsfiddle.net/Limitlessisa/oxhgd32c/
var price="10.000.500,61 TL";
document.getElementById("demo1").innerHTML = price_to_number(price);
var numberPrice="10000500.62";
document.getElementById("demo2").innerHTML = number_to_price(numberPrice);
function price_to_number(v){
if(!v){return 0;}
v=v.split('.').join('');
v=v.split(',').join('.');
return Number(v.replace(/[^0-9.]/g, ""));
}
function number_to_price(v){
if(v==0){return '0,00';}
v=parseFloat(v);
v=v.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
v=v.split('.').join('*').split(',').join('.').split('*').join(',');
return v;
}
You can try this
var str = "$1,112.12";
str = str.replace(",", "");
str = str.replace("$", "");
console.log(parseFloat(str));
let thousands_seps = '.';
let decimal_sep = ',';
let sanitizeValue = "R$ 2.530,55".replace(thousands_seps,'')
.replace(decimal_sep,'.')
.replace(/[^0-9.-]+/, '');
// Converting to float
// Result 2530.55
let stringToFloat = parseFloat(sanitizeValue);
// Formatting for currency: "R$ 2.530,55"
// BRL in this case
let floatTocurrency = Number(stringToFloat).toLocaleString('pt-BR', {style: 'currency', currency: 'BRL'});
// Output
console.log(stringToFloat, floatTocurrency);
I know you've found a solution to your question, I just wanted to recommend that maybe you look at the following more extensive jQuery plugin for International Number Formats:
International Number Formatter
How about simply
Number(currency.replace(/[^0-9-]+/g,""))/100;
Works with all currencies and locales. replaces all non-numeric chars (you can have €50.000,00 or $50,000.00) input must have 2 decimal places
jQuery.preferCulture("en-IN");
var price = jQuery.format(39.00, "c");
output is: Rs. 39.00
use jquery.glob.js,
jQuery.glob.all.js
Here's a simple function -
function getNumberFromCurrency(currency) {
return Number(currency.replace(/[$,]/g,''))
}
console.log(getNumberFromCurrency('$1,000,000.99')) // 1000000.99
For currencies that use the ',' separator mentioned by Quethzel Diaz
Currency is in Brazilian.
var currency_br = "R$ 1.343,45";
currency_br = currency_br.replace('.', "").replace(',', '.');
var number_formated = Number(currency_br.replace(/[^0-9.-]+/g,""));
var parseCurrency = function (e) {
if (typeof (e) === 'number') return e;
if (typeof (e) === 'string') {
var str = e.trim();
var value = Number(e.replace(/[^0-9.-]+/g, ""));
return str.startsWith('(') && str.endsWith(')') ? -value: value;
}
return e;
}
This worked for me and covers most edge cases :)
function toFloat(num) {
const cleanStr = String(num).replace(/[^0-9.,]/g, '');
let dotPos = cleanStr.indexOf('.');
let commaPos = cleanStr.indexOf(',');
if (dotPos < 0) dotPos = 0;
if (commaPos < 0) commaPos = 0;
const dotSplit = cleanStr.split('.');
const commaSplit = cleanStr.split(',');
const isDecimalDot = dotPos
&& (
(commaPos && dotPos > commaPos)
|| (!commaPos && dotSplit[dotSplit.length - 1].length === 2)
);
const isDecimalComma = commaPos
&& (
(dotPos && dotPos < commaPos)
|| (!dotPos && commaSplit[commaSplit.length - 1].length === 2)
);
let integerPart = cleanStr;
let decimalPart = '0';
if (isDecimalComma) {
integerPart = commaSplit[0];
decimalPart = commaSplit[1];
}
if (isDecimalDot) {
integerPart = dotSplit[0];
decimalPart = dotSplit[1];
}
return parseFloat(
`${integerPart.replace(/[^0-9]/g, '')}.${decimalPart.replace(/[^0-9]/g, '')}`,
);
}
toFloat('USD 1,500.00'); // 1500
toFloat('USD 1,500'); // 1500
toFloat('USD 500.00'); // 500
toFloat('USD 500'); // 500
toFloat('EUR 1.500,00'); // 1500
toFloat('EUR 1.500'); // 1500
toFloat('EUR 500,00'); // 500
toFloat('EUR 500'); // 500
Such a headache and so less consideration to other cultures for nothing...
here it is folks:
let floatPrice = parseFloat(price.replace(/(,|\.)([0-9]{3})/g,'$2').replace(/(,|\.)/,'.'));
as simple as that.
$ 150.00
Fr. 150.00
€ 689.00
I have tested for above three currency symbols .You can do it for others also.
var price = Fr. 150.00;
var priceFloat = price.replace(/[^\d\.]/g, '');
Above regular expression will remove everything that is not a digit or a period.So You can get the string without currency symbol but in case of " Fr. 150.00 " if you console for output then you will get price as
console.log('priceFloat : '+priceFloat);
output will be like priceFloat : .150.00
which is wrong so you check the index of "." then split that and get the proper result.
if (priceFloat.indexOf('.') == 0) {
priceFloat = parseFloat(priceFloat.split('.')[1]);
}else{
priceFloat = parseFloat(priceFloat);
}
function NumberConvertToDecimal (number) {
if (number == 0) {
return '0.00';
}
number = parseFloat(number);
number = number.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1");
number = number.split('.').join('*').split('*').join('.');
return number;
}
This function should work whichever the locale and currency settings :
function getNumPrice(price, decimalpoint) {
var p = price.split(decimalpoint);
for (var i=0;i<p.length;i++) p[i] = p[i].replace(/\D/g,'');
return p.join('.');
}
This assumes you know the decimal point character (in my case the locale is set from PHP, so I get it with <?php echo cms_function_to_get_decimal_point(); ?>).
You should be able to handle this using vanilla JS. The Internationalization API is part of JS core: ECMAScript Internationalization API
https://www.w3.org/International/wiki/JavaScriptInternationalization
This answer worked for me: How to format numbers as currency strings

Javascript Function defaulting to wrong answer (I think)

Hi can somebody tell me why the output to my function defaults to even when you insert over 17 numbers? It's probably super simple, please go easy on me!
function oddOrEven(number) {
var number = document.getElementById('number').value;
if(number % 2 != 0) {
document.getElementById('demo').innerHTML = "Odd";
}
else {
document.getElementById('demo').innerHTML = "Even";
}
if (number.length === 0) {
document.getElementById('demo').innerHTML = "Odd / Even";
}
}
You can simplify this whole thing. If you are always grabbing the input with id 'number' you don't need to pass a param, and then after a simple test you can inline the answer you want:
function oddOrEven(){
var val = document.getElementById('number').value;
var number = parseInt(val, 10);
// if it's not a valid number, you'll have NaN here which is falsy
if (number) {
document.getElementById('demo').innerHTML = (number % 2) ? "Even" : "Odd";
}
}
All that said, I just caught that you're talking about 17 digits (thanks to #JJJ's comment) rather than using the function more than once. The problem in this case is that JS integers have a size limit. If you parse anything larger it returns a number you're not going to expect. There are a lot of discussion of general handling of very large numbers here: http://2ality.com/2012/07/large-integers.html, but for your modulus problem you could take the last digit and check if that's odd or even like so:
function oddOrEven(){
var val = document.getElementById('number').value;
var number = parseInt(val, 10);
// if it's not a valid number, you'll have NaN here which is falsy
if (number) {
var lastDigit = val[val.length-1];
document.getElementById('demo').innerHTML = (parseInt(lastDigit, 10) % 2) ? "Even" : "Odd";
}
}

price_from.toFixed() is not a function

pretty simple issue here, this was working before but not anymore.
heres my code:
$('.filter-price').submit(function(e) {
var alert_message = '';
var price_from = $('.filter-price #price_from').val();
var price_to = $('.filter-price #price_to').val();
if (isNaN(price_from) || isNaN(price_to))
{
if (isNaN(price_from))
{
alert_message += "Price from must be a number, i.e. 500\n";
$('.filter-price #price_from').val('From');
}
if (isNaN(price_to))
{
alert_message += "Price to must be a number, i.e. 500\n";
$('.filter-price #price_to').val('To');
}
}
else
{
price_from = price_from.toFixed();
price_to = price_to.toFixed();
if (price_from >= price_to)
{
alert_message += "Price from must be less than price to\n";
$('.filter-price #price_from').val('From');
$('.filter-price #price_to').val('To');
}
}
if (alert_message != '')
{
e.preventDefault();
alert(alert_message);
}
});
now web developer is giving me the error "price_from.toFixed is not a function" and my javascript is not working.
val returns a string; toFixed operates on numbers. Convert your string to a number like this:
Number(price_from).toFixed();
Note: You're checking whether the string contains a number using isNaN. This works because isNaN does an implicit number conversion before testing. To use any of the number methods, however, you'll need to do this same conversion explicitly, as shown above.
Don't confuse the JavaScript type of the object with what it represents. A string can contain a "number" in string form and still be just a string.
First of all 'isNaN' function does not REALLY check whether string represents number. For example isNaN('456a') returns true, but '456a' is not number at all. For this purpose you need other method of checking. I would suggest to use regular expressions.
Then you need to parse string for compareing numbers ( i.e. price_from < price_to ).
Here is the modificated code you may assume:
$('.filter-price').submit(function(e) {
var alert_message = '';
var price_from = $('.filter-price #price_from').val();
var price_to = $('.filter-price #price_to').val();
var isNumberRegExp = new RegExp(/^[-+]?[0-9]+(\.[0-9]+)*$/);
if (!isNumberRegExp.test(price_from) || !isNumberRegExp.test(price_to))
{
if (!isNumberRegExp.test(price_from))
{
alert_message += "Price from must be a number, i.e. 500\n";
$('.filter-price #price_from').val('From');
}
if (!isNumberRegExp.test(price_to))
{
alert_message += "Price to must be a number, i.e. 500\n";
$('.filter-price #price_to').val('To');
}
}
else
{
price_from = parseFloat(price_from);
price_to = parseFloat(price_to);
if (price_from >= price_to)
{
alert_message += "Price from must be less than price to\n";
$('.filter-price #price_from').val('From');
$('.filter-price #price_to').val('To');
}
}
if (alert_message != '')
{
e.preventDefault();
alert(alert_message);
}
});

Javascript to enter only positive or negative decimal number with 3 decimal places into a ASP.NET TextBox

I have one TextBox in my UserControl. Here I want enter only positive or negative decimal number with three decimal places.
For example like below:
128.324, -23.453, 10, 0.453, -2, 2.34, -5.34
The TextBox should not allow to enter other characters. How to do this using JavaScript? I am not good enough in JavaScript.
If you validate on change your should be alright. Make sure you also validate any data that is sent to the server, on the server, since any data can be sent no matter how you try to validate it with JS:
var input = document.getElementById('tehinput');
input.onchange = function(){
var val = this.value, sign = '';
if(val.lastIndexOf('-', 0) === 0){
sign = '-';
val = val.substring(1);
}
var parts = val.split('.').slice(0,2);
if(parts[0] && parseInt(parts[0], 10).toString() !== parts[0]){
parts[0] = parseInt(parts[0], 10);
if(!parts[0])
parts[0] = 0;
}
var result = parts[0];
if(parts.length > 1){
result += '.';
if(parts[1].length > 3 ||
parseInt(parts[1], 10).toString() !== parts[1]){
parts[1] = parseInt(parts[1].substring(0,3), 10);
if(!parts[1])
parts[1] = 0;
}
result += parts[1];
}
this.value = sign+result;
}
JSFiddle
A regular expression to check content would be something like:
var re = /^[+-]?[\d,]+(\.\d{3})?$/;
but that will not enforce a comma for thousands, only allow it somewhere in the integer part. Note that in some countries, a comma is used for the decimal point.

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