charcode comparison against raw interger and stored value give different results - javascript

Whenever I compare a charcode from an index to a raw integer i get the proper response. When I store that same integer in a variable and use the variable to make the comparison, my result is different. Why?
var f = "What a wonderful world";
let newline = 10; //unicode doesnt work '\u000A'; //charcode (10);
let space = 32; //unicode doesn't work '\u0020' //charcode (32);
var test = f.charCodeAt(4);
console.log(test);
//returns 32
console.log("space");
//returns " 'is space'"
if (test === 32) console.log("number");
//returns "number"
if (test === space) console.log("variable");
//false

Related

How to convert big number to string value in JavaScript without using any external lib?

Convert the ASCII value sentence to its equivalent string
This is for writing a similar program given above. I tried to convert the input directly to string value for the iteration.
What is happening is, assume the input value is
var num = 23511011501782351112179911801562340161171141148;
When I convert this number to string
num.toString()
I'm getting the result like this:
"2.351101150178235e+46"
There are so many similar questions asked in SOF, but I didn't see any proper answers.
Can someone help me with how to iterate each value in the input?
Thanks in advance.
If I understand you mean correctly, you can replace the code char ch = (char)num; with var ch = String.fromCharCode(num);. Like this:
var result = [];
function asciiToSentence(str, len)
{
var num = 0;
for (var i = 0; i < len; i++) {
// Append the current digit
num = num * 10 + (str[i] - '0');
// If num is within the required range
if (num >= 32 && num <= 122) {
// Convert num to char
var ch = String.fromCharCode(num);
result.push(ch)
// Reset num to 0
num = 0;
}
}
}
var str = "7110110110711510211111471101101107115";
var len = str.length;
asciiToSentence(str, len);
console.log(result.join(''));
Reference: String.fromCharCode()
Explanation:
First, inside the function asciiToSentence, we need 2 parameters str and len (str is a string while len is the length of that string).
Next, we make a temporary num to calculate the number inside the string based on this table: ASCII Printable Characters
We trying to parse one-by-one character to a number and multiply it with 10. Then, we compare it between 32 and 122 (based on the number in the table above).
If the number we have is inside the range, we parse that number to a character using String.fromCharCode function and reset the value num. Otherwise, we continue the loop and increase the value num

Find longest word in Javascript array

So I'm working on this codility coding challenge and I cannot get the code to work for all inputs, particularly large ones. The rules for this are here.
To summarize, I need each word in the string to be tested for: alpha-numeric characters only, even number of letters, and odd number of digits.
For the sample input - "test 5 a0A pass007 ?xy1", this solution effectively ignores "test" (it has an even number of digits, 0 digits) and "?xy1" (special character, ?). From the leftover options, it chooses pass007 as the longest word and returns 7 (length of word).
I start by splitting the string into separate words and then generating if statements to check if each word in my new array meets the requirements, isAlpha, isAlphaEven (remainder 0 for even # of letters), isNumeric (remainder 1 for odd numbers).
Any idea what I am doing wrong? Thanks much! :)
// you can write to stdout for debugging purposes,
// e.g. console.log('this is a debug message');
function solution(S) {
// write your code in JavaScript (Node.js 8.9.4)
// you can write to stdout for debugging purposes,
// e.g. console.log('this is a debug message');
// write your code in JavaScript (Node.js 8.9.4)
var words = S.split(" ");
var isAlpha = /^[0-9a-zA-z]*$/;
var isAlphaEven = /^[a-zA-Z]/;
var isNumeric = /^[0-9]/;
var maxLength = -1;
for(var i = 0; i <= words.length - 1; i++) {
if(words[i].match(isAlpha)
&& words[i].replace(isAlphaEven, '').length % 2 == 0
&& words[i].replace(isNumeric, '').length % 2 == 1
|| words[i].match(isNumeric)
) {
maxLength = Math.max(maxLength, words[i].length);
//console.log(words[i], maxLength);
}
}
return maxLength;
}
One problem is that the patterns
var isAlphaEven = /^[a-zA-Z]/;
var isNumeric = /^[0-9]/;
can only match characters at the start of the string: ^ anchors to the beginning. It also isn't a global match, so it'll only replace one character. Another problem is that you're replacing the matches with the empty string, rather than testing the number of matches. To test the number of matches, use .match instead, with the global flag, and check the length of the resulting array (or null if there are no matches):
function solution(S) {
// write your code in JavaScript (Node.js 8.9.4)
// you can write to stdout for debugging purposes,
// e.g. console.log('this is a debug message');
// write your code in JavaScript (Node.js 8.9.4)
var words = S.split(" ");
var allAlphaNumeric = /^[\da-z]*$/i;
var alpha = /[a-z]/gi;
var numeric = /\d/g;
var maxLength = -1;
for (var i = 0; i <= words.length - 1; i++) {
if (words[i].match(allAlphaNumeric) &&
(words[i].match(alpha) || []).length % 2 == 0 &&
(words[i].match(numeric) || []).length % 2 == 1
) {
maxLength = Math.max(maxLength, words[i].length);
}
}
return maxLength;
}
console.log(solution("test 5 a0A pass007 ?xy1"));
Note that you can use the case-insensitive flag instead of repeating a-zA-Z, and you can use \d instead of [0-9] if you wish.
While you could use .replace to figure out the number of matches, it'd be convoluted: you'd have to replace everything that doesn't match with the empty string, which would make the code's intent somewhat confusing.
You already have the answer why your approach didn't work as expected.
So I thought I could add a slightly different approach with multiple .filter() steps
function findLongestWord(input) {
const isAlphaNumericOnly = /^[a-z0-9]+$/i;
const numbersOnly = /\d/g;
const alphaOnly = /[a-z]/gi;
const validWords = input.split(/\s/)
.filter(word => isAlphaNumericOnly.test(word))
.filter(word => (word.match(numbersOnly) || []).length % 2 === 1)
.filter(word => (word.match(alphaOnly) || []).length % 2 === 0)
.sort((a, b) => b.length - a.length);
return {
word: validWords[0],
length: validWords[0] ? validWords[0].length : -1
};
}
console.log(findLongestWord("test 5 a0A pass007 ?xy1"));

Using parseFloat() or parseInt() and regex in JavaScript (converting a CSV file)

I'm converting a CSV file to a local 2D array. I wanted to know if there is a better way to convert strings to floats/int rather then using regex followed by a parseFloat() / parseInt.
Ideas / Suggestions?
// numex() - checkes to see if the string (str) is a number
// returns number.valid (true||false) and number.value = (float||int||string)
numex = function(str){
number = {};
number.valid = false;
number.value = str;
// if we see a number then convert it to a floating point or integer
if((number.value.search(/[^0-9^\.^\$^\%^\-^\"^,^ ]+/) < 0) && str.length > 0) {
number.valid = true;
number.value = str.replace(/[^\-^0-9^\.]+/g, ''); // TODO add % coversion code for example if we see a 10% covert it to .1
if(number.value.search(/[\.]/) >= 0) {
number.value = parseFloat(number.value); // replace floating point
} else {
number.value = parseInt(number.value); // replace integers
}
}
return number; // number.valid = true or false;
}
var num = numex("1.101");
alert(num.value);
I don't think you need to use regexp at all. Try this:
var num = {};
num.value = new Number(str);
num.valid = !isNaN(num.value);
Number constructor is more strict than parseInt and parseFloat in that it does not accept strings like 10aaa or 1.2bbb so there is no need to perform a regexp check.
I simplified the code greatly and used something similar to what LeZuse did.
isNaN(value) || value == ""
https://github.com/designpro/jCSV

numeric variables in JS

For a variable x=5, how do I know it is number five or the character '5'?
Btw, in JS, do characters follow the ASCII table? Then can I manipulate a character variable. For example, if variable x is character a, can I do x=x+1 to make it character b?
To see if x is the number 5, as opposed to the string "5", you can use the identity operator:
if (x === 5) {
}
Identity will not do any implicit conversions; it will return true only if both operands are equal without any conversions.
For example, if variable x is character a, can I do x=x+1 to make it
character b?
No. x = x + 1 will convert 1 to a string, perform string concatenation and return "a1"
You can use
typeof x;
which returns a string describing the type of the variable, like number, string or object.
To get the character code of a character, use charCodeAt:
var mystring = 'a';
mystring.charCodeAt(0);
And to get a character from an augmented char code, use String.fromCharCode :
var nextLetter = String.fromCharCode( mystring.charCodeAt(0) + 1 ); // returns "b"
This creates a new string from the incremented char code from the first character in mystring.
Just get the type of the variable:
console.log(typeof '5'); // Returns 'string';
console.log(typeof 5); // Returns 'number';
As for your second question, no, it doesn't work:
console.log('b' + 1); // Returns 'b1'
To check if a variable is a number:
if (typeof x == 'number')
// x is a number
Doing this x = x + 1 when x = b, would result in the string 'a1';
If your var x is not an integer, this is the best way to change it to integer..
To change the x to integer
x = parseInt(x);
You can how add any value to the x, example:
x = x + 2;
Since we have changed the x to integer, we can now identify if this is equal to 5
if(x == 5){
//Your Codes Here
}

How to convert a currency string to a double with Javascript?

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

Categories

Resources