Is it possible to parseFloat the whole string? - javascript

As you know, the javascript's parseFloat function works only until it meets an invalid character, so for example
parseFloat("10.123") = 10.123
parseFloat("12=zzzz") = 12
parseFloat("z12") = NaN
Is there a way or an implementation of parseFloat that would return NaN if the whole string is not a valid float number?

Use this instead:
var num = Number(value);
Then you can do:
if (isNaN(num)) {
// take proper action
}

Maybe try:
var f = parseFloat( someStr );
if( f.toString() != someStr ) {
// string has other stuff besides the number
}
Update: Don't do this, use #dcp's method :)

var asFloat = parseFloat("12aa");
if (String(asFloat).length != "12aa".length) {
// The value is not completely a float
}
else {
// The value is a float
}

Related

Can I check on what an integer ends in Javascript

I want to remove the decimals after a price if it ends on ',00'. If it ends on anything else it should remain. I'll have to be able to see on what the price ends to do so, but how do I achieve this in Javascript?
My idea was checking if the price ended on 00 and removing it in an if statement.
function gformFormatMoney(text, isNumeric){
if(!gf_global.gf_currency_config)
return text;
var currency = new Currency(gf_global.gf_currency_config);
var unformatted = currency.toMoney(text, isNumeric);
var formatted;
var formatting = unformatted%10;
if(formatting == 00) {
}
return unformatted;
}
^This gives a error 'Octal litterals with the prefix 0 are not allowed'
You need to parse your numbers as a float, fix it to 2 decimals (in all cases), and remove any matches for (.00). Something like this could work:
function fixFloat(num){
return parseFloat(num).toFixed(2).replace('.00', '');
}
console.log(fixFloat(20.00));
console.log(fixFloat(40.40));
console.log(fixFloat(30.01));
Please be aware that this will return a string. If you wish to convert this back to a number, you'll need to parse it again.
You should use toFixed.
as for :
let num = 50.00;
num.toFixed(2).includes('.00') ? num.toFixed() :num.toFixed(2);
If the data type is not string , the trailing zeros after decimal will be removed. If it is a string use parseInt to convert to number
let price = 20.00;
console.log(price)
let price1 = '40.00'
console.log(parseInt(price1, 10))
let price2 = '40.00'
console.log(parseFloat(price2, 10))
Turns out it wasn't an integer, but a string.
I fixed it by doing:
function gformFormatMoney(text, isNumeric){
if(!gf_global.gf_currency_config)
return text;
var currency = new Currency(gf_global.gf_currency_config);
var unformatted = currency.toMoney(text, isNumeric);
var formatted = unformatted.replace(',00', '');
return formatted;
}

Validating a data input javascript

I have been looking to validate the data input to check whether it is a integer or a string. I looked around and saw some suggestions and typeof suggestions but nothing seems to work.
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
var mk1 = parseInt(mk1);
mark1.push(mk1);
If you want to check whether input string is not a number try this:
if (isNaN(parseInt(name, 10)) {
//name is String
} else {
//name is Number
}
use the === operator as below
if (mk1 === parseInt(mk1 , 10))
alert("mk1 is integer")
else
alert("mk1 is not an integer. May be String")
If you don't know that the argument is a number-
function isInt(n){
return Number(n)===n && n%1===0;
}
Try this way to find input type;
if(!isNaN(parseInt(mk1)))
// for integer
else if(!isNaN(parseFloat(mk1)))
//for float
else
// String
When you prompt() the user for data, you always get a string. If you want to check, whether it actually contains just a number, you can try this:
var value = prompt('...'),
num = parseInt(value, 10);
if (num == value) {
// ... it is an integer, use `num`
} else {
// ... it's not an integer (or not *just* an integer), use `value`
}
(or use parseFloat(value) for real numbers).
It's hard to say what are you trying to do really. You seem to declare var mk1 twice, which looks a bit strange. Also, even if parseInt fails (then returns NaN [Not a Number]) you add it to mark1, which is probably not what you want. Have a look at this:
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
mk1 = parseInt(mk1);
if (Number.isNaN(mk1) === false) {
mark1.push(mk1);
} else {
alert("mark 1 is not a number");
}
Use this function:
isNaN(parseInt(mk1))
It will return "true" if not a number, and "false" if a number

Round the value in Javascript

I have scenario where if user enters for example 000.03, I want to show the user it as .03 instead of 000.03. How can I do this with Javascript?
You can use a regular expression:
"000.03".replace(/^0+\./, ".");
Adjust it to your liking.
This actually is trickier than it first seems. Removing leading zero's is not something that is standard Javascript. I found this elegant solution online and edited it a bit.
function removeLeadingZeros(strNumber)
{
while (strNumber.substr(0,1) == '0' && strNumber.length>1)
{
strNumber = strNumber.substr(1);
}
return strNumber;
}
userInput = "000.03";
alert(removeLeadingZeros(userInput));
How about:
function showRounded(val) {
var zero = parseInt(val.split('.')[0],10) === 0;
return zero ? val.substring(val.indexOf('.')) : val.replace(/^0+/,'') );
}
console.log(showRounded('000.03')); //=> ".03"
console.log(showRounded('900.03')); //=> "900.03"
console.log(showRounded('009.03')); //=> "9.03"
Or adjust Álvaro G. Vicario's solution to get rid of leading zero's into:
String(parseFloat("090.03")).replace(/^0+\./, ".")
This function will take any string and try to parse it as a number, then format it the way you described:
function makePretty(userInput) {
var num,
str;
num = parseFloat(userInput); // e.g. 0.03
str = userInput.toString();
if (!isNaN(num) && str.substring(0, 1) === '0') {
str = str.substring(1); // e.g. .03
} else if (isNaN(num)) {
str = userInput; // it’s not a number, so just return the input
}
return str;
}
makePretty('000.03'); // '.03'
makePretty('020.03'); // '20.03'
It you feed it something it cannot parse as a number, it will just return it back.
Update: Oh, I see If the single leading zero needs to be removed as well. Updated the code.
Assuming your input's all the same format, and you want to display the .
user = "000.03";
user = user.substring(3);
You can convert a string into a number and back into a string to format it as "0.03":
var input = "000.03";
var output = (+input).toString(); // "0.03"
To get rid of any leading zeroes (e.g. ".03"), you can do:
var input = "000.03";
var output = input.substr(input.indexOf(".")); // ".03"
However, this improperly strips "20.30" to ".30". You can combine the first two methods to get around this:
var input = "000.03";
var output = Math.abs(+input) < 1 ?
input.substr(input.indexOf(".")) :
(+"000.03").toString();

jquery - toFixed but not toFixed

Using toFixed like follows gives:
var a=0.5, b=1, c=1.5;
console.log(a.toFixed(), b.toFixed(), c.toFixed());
// 0.5 1.0 1.5
However, when it's a whole number, I only want it to return "1".
Help!
You could use a Regular Expression to remove a trailing .0, if it exists:
Number.prototype.safe_toFixed = function (x) {
var that = this.toFixed(x);
return that.replace(/\.0$/, '');
}
This is what I did and it works every time.
var x= Number(54.03).toFixed(1);
if(Math.floor(x) == x) {
x = Math.floor(x);
}
alert( x );
I am just comparing the two types to see if they match. If they do, then I know there may or may not be an extra zero. Either way, I simply round up (ceil) or down (floor) and get the whole number with no annoying decimal and trailing zero.
You could use split() and a if condition:
var digit = 1.2
var ret = digit.toFixed(1);
var intValue = ret.split('.');
if(intValue[1] == 0){
digit = intValue[0];
}

How to parse float with two decimal places in javascript?

I have the following code. I would like to have it such that if price_result equals an integer, let's say 10, then I would like to add two decimal places. So 10 would be 10.00.
Or if it equals 10.6 would be 10.60. Not sure how to do this.
price_result = parseFloat(test_var.split('$')[1].slice(0,-1));
You can use toFixed() to do that
var twoPlacedFloat = parseFloat(yourString).toFixed(2)
If you need performance (like in games):
Math.round(number * 100) / 100
It's about 100 times as fast as parseFloat(number.toFixed(2))
http://jsperf.com/parsefloat-tofixed-vs-math-round
When you use toFixed, it always returns the value as a string. This sometimes complicates the code. To avoid that, you can make an alternative method for Number.
Number.prototype.round = function(p) {
p = p || 10;
return parseFloat( this.toFixed(p) );
};
and use:
var n = 22 / 7; // 3.142857142857143
n.round(3); // 3.143
or simply:
(22/7).round(3); // 3.143
To return a number, add another layer of parentheses. Keeps it clean.
var twoPlacedFloat = parseFloat((10.02745).toFixed(2));
If your objective is to parse, and your input might be a literal, then you'd expect a float and toFixed won't provide that, so here are two simple functions to provide this:
function parseFloat2Decimals(value) {
return parseFloat(parseFloat(value).toFixed(2));
}
function parseFloat2Decimals(value,decimalPlaces) {
return parseFloat(parseFloat(value).toFixed(decimalPlaces));
}
ceil from lodash is probably the best
_.ceil("315.9250488",2)
_.ceil(315.9250488,2)
_.ceil(undefined,2)
_.ceil(null,2)
_.ceil("",2)
will work also with a number and it's safe
You can use .toFixed() to for float value 2 digits
Exampale
let newValue = parseFloat(9.990000).toFixed(2)
//output
9.99
I have tried this for my case and it'll work fine.
var multiplied_value = parseFloat(given_quantity*given_price).toFixed(3);
Sample output:
9.007
parseFloat(parseFloat(amount).toFixed(2))
You have to parse it twice. The first time is to convert the string to a float, then fix it to two decimals (but the toFixed returns a string), and finally parse it again.
Please use below function if you don't want to round off.
function ConvertToDecimal(num) {
num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
alert('M : ' + Number(num)); //If you need it back as a Number
}
For what its worth: A decimal number, is a decimal number, you either round it to some other value or not. Internally, it will approximate a decimal fraction according to the rule of floating point arthmetic and handling. It stays a decimal number (floating point, in JS a double) internally, no matter how you many digits you want to display it with.
To present it for display, you can choose the precision of the display to whatever you want by string conversion. Presentation is a display issue, not a storage thing.
#sd
Short Answer: There is no way in JS to have Number datatype value with trailing zeros after a decimal.
Long Answer: Its the property of toFixed or toPrecision function of JavaScript, to return the String. The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype. So to achieve the above in JS we have 2 options
Either use data as a string or
Agree to have truncated value with case '0' at the end ex 2.50 -> 2.5.
You can store your price as a string
You can use
Number(string)
for your calculations.
example
Number("34.50") == 34.5
also
Number("35.65") == 35.65
If you're comfortable with the Number function , you can go with it.
Try this (see comments in code):
function fixInteger(el) {
// this is element's value selector, you should use your own
value = $(el).val();
if (value == '') {
value = 0;
}
newValue = parseInt(value);
// if new value is Nan (when input is a string with no integers in it)
if (isNaN(newValue)) {
value = 0;
newValue = parseInt(value);
}
// apply new value to element
$(el).val(newValue);
}
function fixPrice(el) {
// this is element's value selector, you should use your own
value = $(el).val();
if (value == '') {
value = 0;
}
newValue = parseFloat(value.replace(',', '.')).toFixed(2);
// if new value is Nan (when input is a string with no integers in it)
if (isNaN(newValue)) {
value = 0;
newValue = parseFloat(value).toFixed(2);
}
// apply new value to element
$(el).val(newValue);
}
Solution for FormArray controllers
Initialize FormArray form Builder
formInitilize() {
this.Form = this._formBuilder.group({
formArray: this._formBuilder.array([this.createForm()])
});
}
Create Form
createForm() {
return (this.Form = this._formBuilder.group({
convertodecimal: ['']
}));
}
Set Form Values into Form Controller
setFormvalues() {
this.Form.setControl('formArray', this._formBuilder.array([]));
const control = <FormArray>this.resourceBalanceForm.controls['formArray'];
this.ListArrayValues.forEach((x) => {
control.push(this.buildForm(x));
});
}
private buildForm(x): FormGroup {
const bindvalues= this._formBuilder.group({
convertodecimal: x.ArrayCollection1? parseFloat(x.ArrayCollection1[0].name).toFixed(2) : '' // Option for array collection
// convertodecimal: x.number.toFixed(2) --- option for two decimal value
});
return bindvalues;
}
I've got other solution.
You can use round() to do that instead toFixed()
var twoPlacedFloat = parseFloat(yourString).round(2)
The solution that work for me is the following
parseFloat(value)

Categories