Jump to content

Number changing from 3,000.00 to 3.00


bukwus

Recommended Posts

Hi

I'm using a form that uses number_format. It works fine until the number in question gets into the thousands. I can enter "3000", click Calculate and it comes back as "3,000.00" which is perfect. But if I click Calculate again, it changes to "3.00". How can I get it to remain "3,000.00"?

 

Here's the code:

<form action="test.php" method="POST" >
<?php
if (empty($_POST['data1'])) {
	$number = '';
}
else {
	str_replace(",","",$_POST['data1']);
	$number = number_format((double)$_POST['data1'],2);
}
?>
<input type="text" style="40" name="data1" value="<?php echo $number; ?>">
<input type="submit" name="submitCalc" value="Calculate" /><br />
<a href="test.php">Reset Form</a>
</form>

Link to comment
https://forums.phpfreaks.com/topic/260820-number-changing-from-300000-to-300/
Share on other sites

The problem is that there's a comma in the number.

You could check if the input contains a comma and remove it, but this would let the user not be able to use the comma, only dot.

 

The variable $number must be treated as a string up until this point of the script:

$number = str_replace(',', '', $number);

After this, it won't contain any more commas, and you can handle it as a number again! :)

The problem is that there's a comma in the number.

You could check if the input contains a comma and remove it, but this would let the user not be able to use the comma, only dot.

 

Unfortunately I need the number that is displayed on the page to go back to the number formatting that includes a comma. Is there a way to un-format the $POST data, place the un-formatted number in a variable and then format the variable without this happening?

<form action="test.php" method="POST" >
<?php
if (empty($_POST['data1'])) {
	$number = '';
}
else {
	$number = str_replace(',', '', $_POST['data1']);
	$number = number_format($number,2);
}
?>
<input type="text" style="40" name="data1" value="<?php echo $number; ?>">
<input type="submit" name="submitCalc" value="Calculate" /><br />
<a href="test.php">Reset Form</a>
</form>

I made a slight change, can you spot it? =P

Rather than str_replace you could use float_val().

 

or just store the number as a number, and only display it with number_format, saving the original value in the original variable.

I did a slight change to bukuw's script, if you see that bukuw's script does the str_replace on the POST data and save it as the variable $number, but then later cast the post data to a double and use it in the number format. With other words, the str_replace did nothing. It worked just fine with the script I posted.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.