Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

to cast a double 1

Status
Not open for further replies.

poulet

Programmer
Feb 22, 2003
4
US
Hi !

I'm trying to cast a double with many decimal figures to another one with only two decimals

Example : 4.657321654 => 4.65

Thank you.

Poulet
 
I would use sprintf to format a string, and then use that string as a number. Mike
______________________________________________________________________
"Experience is the comb that Nature gives us after we are bald."

Is that a haiku?
I never could get the hang
of writing those things.
 
Why not leave the variable alone, and just control it's output / display with printf for example.
If you must change it perhaps you could do it with a re-ex.
Code:
$new_double = ( $old_double =~ /^(\d+)(\.\d{0,2})/ ) ? $1 . $2 : $old_double;
This code should take reduce it to a maximum of two decimal places. If their is no decimal portion to this number then it will assign the old_double value (an integer). If you must have two decimal places you could use further reg-ex tests on the new double,
check for a decimal, if not assign two 0's:
Code:
unless ($new_double =~ /\./) { $new_double .= ".00"; }
although instead of this we could have written:
Code:
$new_double = ( $old_double =~ /^(\d+)(\.\d{0,2})/ ) ? $1 . $2 : $old_double . ".00";
We now know $new_double must have 1 or 2 post decimal digits, so check for 2nd digit and if not add it:
Code:
unless ($new_double =~ /\.\d{2}/ ) { $new_double .= "0" ; }
, check for 2 numeric
 
regular expressions have a higher overhead than most functions
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top