How to convert a string to number - javascript

I can't figure it out how to convert this string 82144251 to a number.
Code:
var num = "82144251";
If I try the code below the .toFixed() function converts my number back to a string...
Question update:
I'm using the Google Apps Script editor and that must be the issue...
num = parseInt(num).toFixed() // if I just do parseInt(num) it returns 8.2144251E7

You can convert a string to number using unary operator '+' or parseInt(number,10) or Number()
check these snippets
var num1a = "1";
console.log(+num1a);
var num1b = "2";
num1b=+num1b;
console.log(num1b);
var num3 = "3"
console.log(parseInt(num3,10));
var num4 = "4";
console.log(Number(num4));
Hope it helps

It looks like you're looking for the Number() functionality here:
var num = "82144251"; // "82144251"
var numAsNumber = Number(num); // prints 82144251
typeof num // string
typeof numAsNumber // number
You can read more about Number() here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
Hope this helps!

No questions are dumb.
a quick answer:
to convert a string to a number you can use the unary plus.
var num = "82144251";
num = +num;
Doing num = +num is practically the same as doing num = num * 1; it converts the value in a to a number if needed, but after that it doesn't change the value.

var num = "82144251";
num = parseInt(num).toFixed()
console.log(num, typeof num); // string
num = parseFloat(num);
console.log(num, typeof num); // number

var intNum = parseInt("82144251", 10); // intNum is number

I use num-0, since it is easier for inline use.

Related

Greater part of decimal number in js

I have this problem:
Write a function greaterpart that receives a decimal number. The number should be greater than zero.
The function is required to identify the bigger part of the decimal number, whether it’s the integer or
the fractional part, and then alert the bigger part.
For example:
greaterpart(32.45) alerts 45.
and
greaterpart(301.71) alerts 301.
And this is my solution:
function graterpart(x){
if(x<0){
alert("Number can not be null");
}
else{
var x;
var y;
y= parseFloat(x);
var remainder = (y-Math.floor(y))*10000;
if(y>remainder){
alert(y);
} else{
alert(remainder);
}
}
}
graterpart(32.45);
But it is not working as it should be.
What am I doing wrong here? Thanks in advance.
Try this:
<script>
function greaterpart(x){
alert(Math.max.apply(this, x.toString().split('.')));
}
greaterpart(32.45);
</script>
Math.max() will implicitely convert the strings returned by String.prototype.split() into numbers.
If you don't understand the function reformulate it with distinct steps:
Turn the number into a string:
x = x.toString();
Split it at the decimal point:
var parts = x.split('.'); // Is now ["32", "45"]
Get the maximum value:
var greater = Math.max(parts[0], parts[1]);
But there is a shorter way. Keep this in mind:
var result1 = fun(arg1, arg2, arg3);
var result2 = fun.apply(thisValue, [arg1, arg2, arg3]);
The second line looks a little convoluted but does exactly the same as the first. You can use this now to simplify the call to Math.max():
var greater = Math.max.apply(this, parts);
And now output it with console.log() or alert().
Simple convert it to string split by . get two element array parseInt each and compare simplest of all
var s = 56.69;
//console.log(s.toString())
var d = s.toString().split(".");
var greater = (parseInt(d[0],10) > parseInt(d[1],10)) ? d[0] : d[1];
alert(greater);
I think the best will be to convert your decimal to string and then split it by ".", convert both parts to integer and alert the greater part.
function graterpart(x){
if(x < 0){
alert("Number can not be null");
}else{
var str = x.toString();
if(str.indexOf(".") != -1){
var parts = str.split(".");
var first_part = parseInt(parts[0]);
var second_part = parseInt(parts[1]);
alert(Math.max(first_part, second_part));
}else{
alert(x);
}
}
}
graterpart(321.45);
https://jsfiddle.net/x7on7xjk/
It can simply be done like this:
var number = 312.25;
var numberStr = number.toString();
var twoParts = numberStr.split(".");
if ((parseInt(twoParts[0])) > (parseInt(twoParts[1]))){
alert (twoParts[0]);
}else {
alert(twoParts[1]);
}

Reverse a number in javascript

I want to reverse a number t following the tutorial.First I have passed a number as a parameter. I have converted the number to string with to String function. Then I used split("").reverse().join("") to reverse the number.
My code is as follows:
<script type="text/javascript">
function reverse_the_string(num) {
num = String(num);
// str = num.toString;
num.split("").reverse().join("");
return;
}
console.log(reverse_the_string(56789));
</script>
However I get an error undefined? Can anyone explain what is the wrong?
You do not return the result. Use
return num.split("").reverse().join("");
If you use just return, then undefined is returned.
function reverse_the_string(num) {
return String(num).split("").reverse().join("");
}
document.write(reverse_the_string(56789));
Caveat: Reversing works only with small numbers!
Try this (Recursive Method)
function reverseNum(num) {
if(num == 0)return 0;
let x = Math.pow(10, (num + '').length - 1);
return (num % 10) * x + reverseNum(Math.floor(num / 10));
}
console.log(reverseNum(432));
The solution of casting the number into a string and reversing the string is a good solution, BUT it doesn't cover all the cases. There are 2 cases that need to be addressed:
Reversing a negative number it doesn't retain the sign.
Reversing a number that ends with zero(s), after reversing you will have leading zeros, e.g. 12300 the reverse will be "00321" when it should be "321".
Using Regular function
var reversed = parseFloat(num.toString().split("").reverse().join()) * Math.sign(num);
Using Arrow Function
var reversed = num => parseFloat(num.toString().split('').reverse().join('')) * Math.sign(num);
Convert the number variable to a string:
var n = 4557
n = n.toString();
then execute the below code.
//**Reverse the Number In javascript**
var result = "";
function reverseNumber(n){
// reverse the number via loop
for(var i=x.length-1; i>=0; i--){
result+=n[i];
}
return Number(result)
}
var x = prompt("Enter a number : ");
console.log(reverseNumber(x))
In order to reverse number/ string you can refer this method:
(without using slice() and substring() methods)
function reverse(str) {
var rev = "";
number = parseInt(str);
for (; number > 0;) {
rev += number % 10;
number = Math.floor(number / 10)
}
return rev;
}

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

how to parse string to int in javascript

i want int from string in javascript how i can get them from
test1 , stsfdf233, fdfk323,
are anyone show me the method to get the integer from this string.
it is a rule that int is always in the back of the string.
how i can get the int who was at last in my string
var s = 'abc123';
var number = s.match(/\d+$/);
number = parseInt(number, 10);
The first step is a simple regular expression - \d+$ will match the digits near the end.
On the next step, we use parseInt on the string we've matched before, to get a proper number.
You can use a regex to extract the numbers in the string via String#match, and convert each of them to a number via parseInt:
var str, matches, index, num;
str = "test123and456";
matches = str.match(/\d+/g);
for (index = 0; index < matches.length; ++index) {
num = parseInt(matches[index], 10);
display("Digit series #" + index + " converts to " + num);
}
Live Example
If the numbers really occur only at the ends of the strings or you just want to convert the first set of digits you find, you can simplify a bit:
var str, matches, num;
str = "test123";
matches = str.match(/\d+/);
if (matches) {
num = parseInt(matches[0], 10);
display("Found match, converts to: " + num);
}
else {
display("No digits found");
}
Live example
If you want to ignore digits that aren't at the end, add $ to the end of the regex:
matches = str.match(/\d+$/);
Live example
var str = "stsfdf233";
var num = parseInt(str.replace(/\D/g, ''), 10);
var match = "stsfdf233".match(/\d+$/);
var result = 0; // default value
if(match != null) {
result = parseInt(match[0], 10);
}
Yet another alternative, this time without any replace or Regular Expression, just one simple loop:
function ExtractInteger(sValue)
{
var sDigits = "";
for (var i = sValue.length - 1; i >= 0; i--)
{
var c = sValue.charAt(i);
if (c < "0" || c > "9")
break;
sDigits = c + sDigits;
}
return (sDigits.length > 0) ? parseInt(sDigits, 10) : NaN;
}
Usage example:
var s = "stsfdf233";
var n = ExtractInteger(s);
alert(n);
This might help you
var str = 'abc123';
var number = str.match(/\d/g).join("");
Use my extension to String class :
String.prototype.toInt=function(){
return parseInt(this.replace(/\D/g, ''),10);
}
Then :
"ddfdsf121iu".toInt();
Will return an integer : 121
First positive or negative number:
"foo-22bar11".match(/-?\d+/); // -22
javascript:alert('stsfdf233'.match(/\d+$/)[0])
Global.parseInt with radix is overkill here, regexp extracted decimal digits already and rigth trimmed string

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