duankun9280 2014-10-30 21:00
浏览 48

在PHP中处理和添加表单提交中的数字

I've made a simple PHP script that has four form input fields. These fields will receive numbers that represent currency amounts. Then these four numbers should be added and shown as a total.

Right now, I cannot find a way to get the total amount to show decimals.

The currency I'm working with uses comma (,) for decimal delimiting and point (.) for thousands delimiting.

This is my form's HTML code :

<form action="send.php" method="post">

<p>Amount 1:</p>
<p><input name="amount1" value=""></p>

<p>Amount 2:</p>
<p><input name="amount2" value=""></p>

<p>Amount 3:</p>
<p><input name="amount3"  value=""></p>

<p>Amount 4:</p>
<p><input name="amount4" value=""></p>

<p><input type='submit' name='submit' value='Submit'></p>

</form>

This is my PHP code for processing:

<?php
//convert to float
$amount1 = (float)$_POST["amount1"];  // $amount1 = 250,50
$amount2 = (float)$_POST["amount2"];  // $amount2 = 100,25
$amount3 = (float)$_POST["amount3"];  // $amount3 = 300,99
$amount4 = (float)$_POST["amount4"];  // $amount4 = 10,50

echo $amount1; // prints 250
echo $amount2; // prints 100
echo $amount3; // prints 300
echo $amount4; // prints 10

//use number_format() to force comma as decimal and to use 2 decimal places
$total = number_format($amount1 + $amount2 + $amount3 + $amount4,2,",",".");

echo $total; //should print "662,24" , instead prints 662

?>

I've also tried using number_format() before adding the numbers , but that still doesn't work.

Also, is there any way to force commas and points as delimiters , without having to do it for each number?

  • 写回答

1条回答 默认 最新

  • du5739 2014-10-30 21:17
    关注

    Try this,

    //convert to float
    $amount1 = floatval(str_replace(',', '.', $_POST["amount1"])); // $amount1 = 250,50
    $amount2 = floatval(str_replace(',', '.', $_POST["amount2"])); // $amount2 = 100,25
    $amount3 = floatval(str_replace(',', '.', $_POST["amount3"])); // $amount3 = 300,99
    $amount4 = floatval(str_replace(',', '.', $_POST["amount4"])); // $amount4 = 10,50
    

    Float values in PHP use the '.' as the decimal separator. You need to replace your ',' decimal separator from your form input with a '.' so they can be correctly casted to float values.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据