...

View Full Version : //fixed\\get rid of the 0. before this number?



Ranger56
01-03-2006, 10:31 PM
$score = 45/53;
$string = sprintf("%0.02f", $score);
echo $string;


I'm sorry if that code is terrible, but I'm just wondering how to get rid of the 0. before the two decimal places that I want to show.

I tried substr but I guess it doesnt work on variables?
I forgot to put echo before it and it works fine now with this code

$score = 45/53;
$string = sprintf("%.2f", $score);
echo substr("$string", 2,4)

All help is appreciated

Velox Letum
01-03-2006, 11:15 PM
Another method:


<?php
$score = 45/53;
$score *= 100; // This is equivalent to $score = $score * 100. I did this to prevent cluttering of the score division.
echo round($score, 0); // Now round up or down as appropriately, removing any decimal.
?>

Ranger56
01-04-2006, 01:38 AM
Here's my final version:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=ISO-8859-1">
<title>Untitled</title>
</head>
<body>
<?php
$_POST['possiblescore'] = 100;
$string = sprintf($_POST['yourscore'] / $_POST['possiblescore']);
printf("%3d %%", $string*100);
?>

<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>Your Score:</label> <input type="text" name="yourscore" /><br /><br />
<label>Maximum Points:</label> <input type="text" name="possiblescore" /><br />
<input type="submit" name="submit"/>
</form>


</body>
</html>

Element
01-04-2006, 03:26 AM
This is the first time I've seen someone use sprintf link think. A little interesting, but hey, if it works.

Velox Letum
01-04-2006, 04:57 AM
In your example, sprintf() serves absolutely no point...it doesn't do any sort of formatting. Personally I'd do it like this, with a round() function. Also with the bulk of the PHP on top, its a good rule to go by. If you must use printf() such as for an assignment in class, at least don't use a useless sprintf().


<?php
$_POST['possiblescore'] = 100;
$score = $_POST['yourscore']/$_POST['possiblescore'];
$score *= 100;
$score = round($score, 3);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=ISO-8859-1">
<title>Untitled</title>
</head>
<body>
<?php echo $score . '%'; ?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>Your Score:</label> <input type="text" name="yourscore" /><br /><br />
<label>Maximum Points:</label> <input type="text" name="possiblescore" /><br />
<input type="submit" name="submit"/>
</form>


</body>
</html>

The proper printf format for the number and 3 decimal places.


printf("%0.3f %%", ($_POST['yourscore'] / $_POST['possiblescore']) * 100);



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum