Jump to content

from negative to positive


Baabu

Recommended Posts

If you are always going to be dealing with a negative number, you can just multiply that by -1.

 

But if its mixed input and you always want it to be positive, then I'm not sure! sorry!

Link to comment
Share on other sites

I am working on a function for you... that only works with int's atm.... I'm gonna try to get it to work on floats (in case your loss is like 410.22)

 

So unless someone says some built in PHP function I should have one I wrote for you in a few mins

Link to comment
Share on other sites

Hrm, it seems I was overthinking things!!

 

Here you go

 

<?php
function neg2pos($number)
{
return ($number < 0) ? $number * -1 : $number;
}

echo neg2pos(22.22); // returns 22.22
echo neg2pos(-599.22); // returns -599.22

?>

 

I hope it does everything you need it to.

 

And of course you go offline when I finally figure it out :(

Link to comment
Share on other sites

or just negate the variable with a minus sign

 

<?php

function neg2pos($number)
{
    return ($number < 0) ? -$number : $number;
}

 

 

Ooh nice catch!

 

I wonder if there is a way to get this function to be built in to PHP?  one for neg2pos and pos2neg could be useful.

Link to comment
Share on other sites

Good call, I knew there had to be a built in function to handle it.

 

the question though is, is there a pos2neg function built in (the opposite)?

 

Or I guess you could just do

 

$var = abs(20);

$var = -$var

Link to comment
Share on other sites

Good call, I knew there had to be a built in function to handle it.

 

the question though is, is there a pos2neg function built in (the opposite)?

 

neg2pos or pos2neg

 

you just apply the minus sign to switch from one to the other.

 

$profit = 1000;

echo -$profit;    // -1000

 

abs() always returns positive.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.