javascript 01.00 number manipulation - javascript

I have an input with value 03.00 representing number of seconds.
I can't figure out how to make a function that will increment or decrement by one this number formatted like this.
Can anyone help me please?

Try this
function inc(val, by) {
val = parseFloat(val) + (by||1);
return (val >= 10 ? '' : '0') + val.toFixed(2);
}
Decrement is just inc(val, -1) or create a wrapper;

Supposing you have an <input> with id="myInput", you can use following javascript:
document.getElementById("myInput").value="0"+parseFloat(document.getElementById("myInput").value)+1;

Related

get input value with math function in variable

I've got some javascript to change the input value via plus/minus buttons.
I now need to save the value after the value has been decremented in a variable and output it as a number.
The javascript for the decrement looks something like this:
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[id='+fieldName+']').val(currentVal - 1);
var test = parseInt($('input[id='+fieldName+']').val(currentVal - 1).val());
alert(test);
}
So as you can see I'm trying to get the updated value of the input in a variable called 'test', but all I'm getting is a NaN. Any ideas how to output the updated value of the input as a number within my test variable?
As #trincot said we cannot re-produce your situation. But the reason a NaN would be returned is because.
parseInt Returns an integer number parsed from the given string. If the first character cannot be converted to a number, NaN is returned.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
let a = '1'
let b = 'Two'
console.log(parseInt(a));
// 1
console.log(parseInt(b));
// NaN
console.log(parseInt(undefined))
// NaN
You can use double Tilda operator ~~ which behaves like Math.floor() except will return you 0 if the value is not a number.
I believe this is the solution you are looking for:
let inputField = document.querySelector('input[name="fieldName"]');
increment = () => {
let currentValue = ~~inputField.value;
alert(currentValue);
inputField.value = currentValue + 1;
};
decrement = () => {
let currentValue = ~~inputField.value;
alert(currentValue);
if (currentValue > 0) {
inputField.value = currentValue - 1;
}
};
<input type="number" name="fieldName" value="0" />
<button onclick="increment()">+</button>
<button onclick="decrement()">-</button>
Hope this helps,
Something showed up to me.
You are using jquery (I think it's right cause of the $ selector), and you are getting the ID with bracket notation.
Why not using something like
var selector = '#' + fieldName;
Then
$(selector)???
Another thing, usually when I'm trying something with javascript, I try it into the developer tool's console of my browser.
Doing it step by step avoid mistakes

Javascript Logical Operator not validating

A simple javascript logical operator validation is not working for me.
eg. Target Price should not be greater than orginal price
x = input from user;
y = 1000; // fixed
if(x > 1000 )
{
alert ( x+'should not be greater than'+y);
}
else
{
alert ( ' proceed' );
}
here is my EXAMPLE
Those values are of type string, you need to convert them to number. You can use Number() for that.
targetPrice = Number($('#pdiwap_dropamt').val());
orginalPrice = Number($('#orgprice_wap').val());
You are compering two strings. Use something like this
if (parseInt(targetPrice) > parseInt(orginalPrice))
Because both the operands string so it does a string comparison.
You can convert the values to a number and then do the comparison like
targetPrice = +$('#pdiwap_dropamt').val();
orginalPrice = +$('#orgprice_wap').val();
Just use the parseInt function to validate correctly. Bucause html input gives the value in string format.
if (parseInt(targetPrice,10) > parseInt(orginalPrice,10))
Updated Link
I think the problem is from the input you're getting which is seen as a string. Try converting to integer first before comparing.
e.g x = parseInt(Input from user);
Yes! it input value is a string so its not validate properly.
Try This.
var x = document.getElementById("input").value;
var y = 1000;
if(!isNaN(x) && x < 1000) {
alert ('proceed' );
} else {
alert(x+'should not be greater than'+y);
}

remove decimal in javascript

I want to remove decimal from number in javascript:
Something like this:
12 => 12
12.00 => 1200
12.12 => 1212
12.12.12 => error: please enter valid number.
I can not use Math.round(number). Because, it'll give me different result. How can I achieve this? Thanks.
The simplest way to handle the first three examples is:
function removeDecimal(num) {
return parseInt(num.toString().replace(".", ""), 10);
}
This assumes that the argument is a number already, in which case your second and fourth examples are impossible.
If that's not the case, you'll need to count the number of dots in the string, using something like (trick taken from this question):
(str.match(/\./g) || []).length
Combining the two and throwing, you can:
function removeDecimal(num) {
if ((num.toString().match(/\./g) || []).length > 1) throw new Error("Too many periods!");
return parseInt(num.toString().replace(".", ""), 10);
}
This will work for most numbers, but may run into rounding errors for particularly large or precise values (for example, removeDecimal("1398080348.12341234") will return 139808034812341230).
If you know the input will always be a number and you want to get really tricky, you can also do something like:
function removeDecimal(num) {
var numStr = num.toString();
if (numStr.indexOf(".") === -1) return num;
return num * Math.pow(10, numStr.length - numStr.indexOf(".") - 1);
}
You can use the replace method to remove the first period in the string, then you can check if there is another period left:
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
// invalid input
}
Demo:
function reformat(str) {
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
return "invalid input";
}
return str;
}
// show in Stackoverflow snippet
function show(str) {
document.write(str + '<br>');
}
show(reformat("12"));
show(reformat("12.00"));
show(reformat("12.12"));
show(reformat("12.12.12"));
How about number = number.replace(".", ""); ?

How can we unable to entry if first number is 0. Read Below for the detail :

How can we unable to entry if first number is 0 in textbox. For example :
If anyone enters :
000000000 - Do not accept
0000001 - accept
0000001002 - accept
0 - Do not accept
If any one have an idea kindly share to me.
You can use parseInt, parseFloat to convert to number and compare it with zero.
if(parseInt(num) > 0)
{
}
if it is number and you do not have to convert it to number then you do not need to use parseInt.
if(num > 0)
{
}
Convert the input string to a number, then:
if(inputNumber%10 == 0) {/*run deny code*/} else {/*run accept code*/}
Finally i got the answer, its a minor task !
int idd = Convert.ToInt16(hour_value.text);
int p = 0;
if (idd > p)
{
}
else
{
}

How do I add an integer value with javascript (jquery) to a value that's returning a string?

I have a simple html block like:
<span id="replies">8</span>
Using jquery I'm trying to add a 1 to the value (8).
var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);
What's happening is it is appearing like:
81
then
811
not 9, which would be the correct answer. What am I doing wrong?
parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.
var currentValue = parseInt($("#replies").text(),10);
The second paramter (radix) makes sure it is parsed as a decimal number.
Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used
var currentValue = parseInt($("#replies").text(),10);
The integer is being converted into a string rather than vice-versa. You want:
var newValue = parseInt(currentValue) + 1
parseInt didn't work for me in IE. So I simply used + on the variable you want as an integer.
var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);
In regards to the octal misinterpretation of .js - I just used this...
parseInt(parseFloat(nv))
and after testing with leading zeros, came back everytime with the correct representation.
hope this helps.
to increment by one you can do something like
var newValue = currentValue ++;
Simply, add a plus sign before the text value
var newValue = +currentValue + 1;
Your code should like this:
<span id="replies">8</span>
var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);
Hacks N Tricks
var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );
I simply fixed your month issue, getMonth array start from 0 to 11.
You can multiply the variable by 1 to force JavaScript to convert the variable to a number for you and then add it to your other value. This works because multiplication isn't overloaded as addition is. Some may say that this is less clear than parseInt, but it is a way to do it and it hasn't been mentioned yet.
You can use parseInt() method to convert string to integer in javascript
You just change the code like this
$("replies").text(parseInt($("replies").text(),10) + 1);

Categories