I am new to using D3.js and I am having problems converting string data into a number. I am using a CSV with one column called "Belgium" composed by numbers like these ones: 54,345 or 1,234,567.
I tried to convert them into numbers by using
data.forEach(function(d) {
d.Belgium = +d.Belgium;
}
but I get NaN as a result. I also tried using
d.Belgium = parseInt(d.Belgium);
but it takes the figures before the first comma and removes the rest of the number. For example, if one number is 1,234,562, using parseInt() I just get 1. If the figure is 982,381, it remains 982.
Remove all , with string.replace(searchvalue, newvalue):
parseInt(str.replace(/,/g, ""))
so for example:
console.log(parseInt("1,234,562".replace(/,/g, "")))
As noted below, use parseFloat instead of parseInt if your numbers may contain decimals e.g. 3.141,592 to keep the floating point number.
I took a bit of a different approach. I used .split(",") to split the value into an array at every ,, then used .join("") to join each index of the array with empty spaces. Used the + operator for ease of use but could have been parseFloat() as well.
let stringNumber = "1,250,234.093";
let numStringNumber = +stringNumber.split(",").join("");
console.log(numStringNumber);
console.log(typeof numStringNumber);
Related
In JS, I do have a float number which come from php as below:
var number = 2,206.00
In JS, I need to use parseFloat that number.
So I tried parseFloat(number), but its give only 2. So how can I get 2206.00 instead of 2?
Number.parseFloat is the same function object as globalThis.parseFloat.
If globalThis.parseFloat encounters a character other than:
a plus sign or,
a minus sign or,
a decimal point or,
an exponent (E or e)
...it returns the value up to that character, ignoring the invalid character and characters following it. A second decimal point also stops parsing.
So the following prints 2. And this seems to be your problem.
console.log(parseFloat('2,206.00')) // 2
Solution: use string manipulation to remove any commas from the number (really a String before parsing it.
console.log(parseFloat('2,206.00'.replaceAll(',', ''))) // 2206
If you need to store the value as a number but render it as a formatted string, you may need Number#toFixed to render the values after the decimal point:
console.log((2206).toFixed(2)) // '2206.00'
Final note: be careful about localization because some countries use commas for decimal points and decimal points for number grouping. As #t.niese says: store number values without localization, and then apply localization at the surface of your app. But that is a wider, more complicated topic.
You have to remove comma first and use parseFloat.
And about 2 decimal after dot, I see you use number_format($myNumber, 2) in PHP, so in JS, you use .toFixed(2).
var number = '2,206.00';
var result = parseFloat(number.replace(/,/g, '')).toFixed(2);
console.log(result);
First of all what you currently have most probably would trigger an Unexpected number error in JS.
It seems the generated value comes from the number_format() PHP function which returns a string. Moreover the var number variable should also be considered a string as we have a string format.
So firstly you should quote var number = '2,206.00' after that, you have to make the string float-like in order to parse it as float so we should replace , with empty string in order for the number to become 2206.00 number = number.replace(",",""). Lastly the parse should be done now in order to convert the float-like string to an actual float parseFloat(number).
Whole code:
var number = '2,206.00';
number.replace(",","");
number = parseFloat(number);
ok, basically you want a two decimal number after point like (20.03),
try this
parseFloat(number).toFixed(2)
I have a string below that is a price in £, I want to remove the currency symbol and then convert this into a number/price I can use to compare against another value (eg. X >= Y ...)
£14.50
I have previously converted strings to numbers used for currency with
var priceNum = parseFloat(price);
IDEAL OUTCOME
14.50 as a number value. Can this be done in a single line?
I found this very helpful
var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9\.-]+/g,""));
Convert (Currency) String to Float
If the currency symbol will always be there, just use substring:
var priceNum = parseFloat(price.substring(1));
If it may or may not be there, you could use replace to remove it:
var priceNum = parseFloat(price.replace(/£/g, ""));
Beware that parseFloat("") is 0. If you don't want 0 for an empty input string, you'll need to handle that. This answer has a rundown of the various way to convert strings to numbers in JavaScript and what they do in various situations.
Side note: Using JavaScript's standard numbers for currency information is generally not best practice, because if things like the classic 0.1 + 0.2 issue (the result is 0.30000000000000004, not 0.3). There are various libraries to help, and BigInt is coming to JavaScript as well (it's a Stage 3 proposal at the moment, currently shipping in Chrome). BigInt is useful because you can use multiples of your basic currency (for instance, * 100 for pounds and pence).
try this number-formatter-npm library. This library is fantastic.
npm i number-formatter-npm
documentation:https://www.npmjs.com/package/number-formatter-npm
There are a few Javascript functions available to convert anything into its equivalent number. Number() operates on an Object, valueOf(), parseFloat, parseInt() are also available.
I have an array which stores numbers 0-9 and decimal point, the elements of the array taken together represents a number. What is the best way to convert this array into a number, whole or fractional?
EDIT: Apologies if I were not clear before. The array, holding the 0-9 characters and possibly a decimal point, could represent either a whole number(without the decimal obviously) or a fractional number. So please suggest something that works for both cases. Thanks.
Try this
var a = [1,2,3,".",2,3];
var num = +a.join("");
What is the best way to convert this array into a number, whole or fractional?
Firstly to combine your array elements you should use Array.join().
You will then have a concatenated variable of your values and decimal. To convert this to a whole number, use parseInt(), and to a floating point number use parseFloat(). You can use the unary + operator (which acts similarly to parseFloat), however in my opinion it is not the best choice semantically here, as you seem to want a specific type of number returned.
Example:
var arr = ['1','.','9','1'];
var concat = arr.join();
var whole = parseInt(concat);
var floating = parseFloat(concat);
Also, parseInt will trim the decimal portion of your number, so if you need rounding you can use:
var rounded = Math.round(parseFloat(concat));
You could use the split property of the string. It splits all the characters into an zero based array.
var charSplits = "this is getting split.";
var splitArr = charSplits.split();
Console.log(splitArr);
// this returns i
Console.log(splitArr[2]);
Background: I would like to add and subtract numbers. I'm using HTML data-attributes. parseInt() and Number() aren't working as I thought they would be.
<div class="originalNumber" data-original-number="1,000,000">1,000,000</div>
<div class="bucket1" data-bucket="100,000">100,000</div>
<div class="bucket2" data-bucket="200,000">200,000</div>
<div class="bucket3" data-bucket="300,000">300,000</div>
I get the original number:
var getOriginal=$(".originalNumber").data("original-number");
console.log = 1,000,000
Now I would like to add and subtract from it. For example click bucket1 and 1,000,000 becomes 900,000 (1,000,000-100,000)
The problem is that I cannot turn the string into a number. I've tried using parseInt() and Number() to no avail.
var getOriginal=parseInt(getOriginal);
console.log(getOriginal);
returns 1
var getOriginal=Number(getOriginal);
console.log(getOriginal);
returns NaN
What am I missing here?
Try using a regex:
var getOriginalNumeric = parseInt(getOriginal.replace(/[^\d\.]/gi, ''));
This will strip out anything but digits and decimals.
You'll need to remove all the commas from the string containing the number before using parseInt().
This question has some information on the best ways to do that.
The problem is that a comma is interpreted as the decimal sign, this is standard for most countries, but the US (for example) uses periods as the decimal separator.
You'd need to replace the comma's:
getOriginal = parseInt(getOriginal.replace(/,/g, ""), 10);
Here's a live example: http://codepen.io/TheDutchCoder/pen/WbbzJL
I'm trying to insert two numbers in two input type text fields. After I do that, I have to make sure than the first number is smaller than the second. To do this, I'm capturing both fields like this:
var supt = $('#suptotal').val();
var supc = $('#supcubierta').val();
When I compare the two variables, they are strings, so for example 21 is considered bigger than 123.
I've tried to use the function ParseInt, like this
var supt = ParseInt($('#suptotal').val());
but it didn't work. How can I compare the numbers as numbers?
use parseInt($('#suptotal').val(), 10) as against ParseInt($('#suptotal').val(), 10)
The function names are case sensitive
parseInt( $('#suptotal').val(), 10 );
Specify a radix as well, incase the string contains something like '010' which would be interpreted as an octal and result in 8.
ParseInt($('#suptotal').val());
You've written the function incorrectly. parseInt is defined in a lowerCamelCase style.
parseInt($('#suptotal').val());
It is also advised that you specify the radix parameter with 10 for base 10.
parseInt($('#suptotal').val(), 10);
But if you are simply wanting to convert the string into a number, use the unary effect of the binary operator +, which will coerce a value into a number when used on a single operand:
var supt = +$('#suptotal').val();