Reputation: 307
I want to create a button on the calculator that could convert a positive number into a negative one and also could change a negative number into a positive number.
Here is the code in js:
function reverse_num(){
var num = $( "#p").text();
if(num > 0){
$("p").prepend("-");
}
else if(num = 0)
{
$("p");
}
}
When I want to convert a positive into a negative, it works fine. But I have no idea what to do when I want to remove that negative sign.
Could someone show me how to do?
Upvotes: 3
Views: 5354
Reputation: 2058
You could use this by two way
Way 1
: You can remove "-"
by using replace('-', '')
;
Way 2
: You can also use multiplication
by (-1)
function reverse_num(){
var num = $( "#p").text();
if(num > 0){
$("p").prepend("-");
}
else if(num < 0){
var num = $( "#p").text().replace('-', '');
$("#p").text(num);
}
else if(num == 0){
$("#p");
}
}
reverse_num();
function reverse_num_version_2(){
var num = $( "#number").text();
if(num > 0){
$("#number").prepend("-");
}
else if(num < 0){
num = num * (-1);
$("#number").text(num);
}
else if(num == 0){
$("#number");
}
}
reverse_num_version_2();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p id="p">-100</p>
<div id="number">-100</div>
Upvotes: 1
Reputation: 770
You should use basic math and multiply by -1 when the minus sign is clicked.
e.g.:
//Get the number
var number = parseFloat( $( "#p").text() );
//Reverse it
function reverse_num(num) {
return (-num); // == (-1 * num)
}
//Replace the content of #p
$("#p").text( reverse_num(number) );
As a "oneliner"
$("#p").text(-(parseFloat($("#p").text())));
Upvotes: 1