Что @Laurenz сказал.
Но почему появляется «странное» сообщение об ошибке?
Ваш синтаксическая ошибка (0,8 вместо 0.8 в cour_g=(((upox_sum+epil_sum)/2)*0,8);) запутывается добавленным бесплатные круглые скобки, который интерпретируется как ROW конструкторы — ведущее ключевое слово ROW является необязательным шумом.
Что вы видите в сообщении об ошибке:
ERROR: invalid input syntax for type numeric: «(0.0000000000000000,8)»
… это выражение строки, состоящий из полей: 0.0000000000000000 и 8.
Без вводящих в заблуждение скобок задание:
cour_g=((upox_sum+epil_sum)/2)*0,8; -- still incorrect: 0,8
… привело бы к другому (более показательному) сообщению об ошибке:
ERROR: query «SELECT ((upox_sum+epil_sum)/2)*0,8» returned 2 columns
Потому что запятая (,) интерпретируется как разделитель столбцов.
This message also reveals that PL/pgSQL evaluates every bare expression with a (basic and fast) SELECT statement internally. The language is basically a wrapper around the core SQL engine. This explains why assignments are slightly more expensive than one might expect coming from other PLs.
Исходное утверждение эквивалентно более подробному синтаксису ROW:
cour_g=ROW(((upox_sum + epil_sum)/2)*0,8); -- still incorrect: 0,8
… что эквивалентно функционально:
cour_g=(SELECT ROW(((upox_sum + epil_sum)/2)*0,8)); -- still incorrect: 0,8
Оба приводят к одному и тому же сообщению об ошибке, которое вы наблюдали.
Или же:
cour_g=(SELECT ((upox_sum + epil_sum)/2)*0,8); -- still incorrect: 0,8
С другим (уже более показательным) сообщением об ошибке:
ERROR: subquery must return only one column
Скобки вокруг вложенного явного SELECT являются обязательными. Если вы отбрасываете ненужный SELECT, снимите с ним заключительные скобки, или они интерпретируются как конструктор ROW (с шумовым словом ROW или без него).
Так что используйте:
cour_g := (upox_sum + epil_sum) / 2 * 0.8;
Скобки вокруг ((upox_sum+epil_sum)/2) также излишни, потому что * и / совместно используют один и тот же приоритет оператора и в любом случае оцениваются слева направо. Но в этом случае добавленные круглые скобки представляют собой безобидный шум (который может улучшить или не улучшить читаемость).
Или упростите до:
cour_g := (upox_sum + epil_sum) * 0.4;
Тем не менее, поскольку присваивания в PL / pgSQL относительно дороги, попробуйте принять стиль программирования с меньшим количеством присваиваний.
И не все безвозмездные скобки безобидны.
462 votes
21 answers
Get the solution ↓↓↓
Recently updated to PHP 7.1 and start getting following error
Warning: A non-numeric value encountered in on line 29
Here is what line 29 looks like
$sub_total += ($item['quantity'] * $product['price']);
On localhost all works fine..
Any ideas how to tackle this or what it is ?
2021-12-22
Write your answer
917
votes
Answer
Solution:
Not exactly the issue you had but the same error for people searching.
This happened to me when I spent too much time on JavaScript.
Coming back to PHP I concatenated two strings with+
instead of.
and got that error.
799
votes
Answer
Solution:
It seems that in PHP 7.1, a Warning will be emitted if a non-numeric value is encountered. See this link.
Here is the relevant portion that pertains to the Warning notice you are getting:
New E_WARNING and E_NOTICE errors have been introduced when invalid
strings are coerced using operators expecting numbers or their
assignment equivalents. An E_NOTICE is emitted when the string begins
with a numeric value but contains trailing non-numeric characters, and
an E_WARNING is emitted when the string does not contain a numeric
value.
I’m guessing either $item[‘quantity’] or $product[‘price’] does not contain a numeric value, so make sure that they do before trying to multiply them. Maybe use some sort of conditional before calculating the $sub_total, like so:
<?php
if (is_numeric($item['quantity']) && is_numeric($product['price'])) {
$sub_total += ($item['quantity'] * $product['price']);
} else {
// do some error handling...
}
901
votes
Answer
Solution:
You can solve the problem without any new logic by just casting the thing into the number, which prevents the warning and is equivalent to the behavior in PHP 7.0 and below:
$sub_total += ((int)$item['quantity'] * (int)$product['price']);
(The answer from Daniel Schroeder is not equivalent because $sub_total would remain unset if non-numeric values are encountered. For example, if you print out $sub_total, you would get an empty string, which is probably wrong in an invoice. — by casting you make sure that $sub_total is an integer.)
572
votes
Answer
Solution:
In my case it was because of me used+
as in other language but in PHP strings concatenation operator is.
.
839
votes
Answer
Solution:
Hello,
In my case using (WordPress) and PHP7.4 I get a warning about numeric value issue. So I changed the old code as follow:
From:
$val = $oldval + $val;
To:
$val = ((int)$oldval + (int)$val);
Now the warning disappeared
826
votes
Answer
Solution:
I had this issue with my pagination forward and backward link …. simply set (int ) in front of the variable $Page+1 and it worked…
<?php
$Page = (isset($_GET['Page']) ? $_GET['Page'] : '');
if ((int)$Page+1<=$PostPagination) {
?>
<li> <a href="Index.php?Page=<?php echo $Page+1; ?>"> »</a></li>
<?php }
?>
237
votes
Answer
Solution:
This was happening to me specifically on PHPMyAdmin. So to more specifically answer this, I did the following:
In File:
C:amppsphpMyAdminlibrariesDisplayResults.class.php
I changed this:
// Move to the next page or to the last one
$endpos = $_SESSION['tmpval']['pos']
+ $_SESSION['tmpval']['max_rows'];
To this:
$endpos = 0;
if (!empty($_SESSION['tmpval']['pos']) && is_numeric($_SESSION['tmpval']['pos'])) {
$endpos += $_SESSION['tmpval']['pos'];
}
if (!empty($_SESSION['tmpval']['max_rows']) && is_numeric($_SESSION['tmpval']['max_rows'])) {
$endpos += $_SESSION['tmpval']['max_rows'];
}
Hope that save’s someone some trouble…
207
votes
Answer
Solution:
I encountered the issue in phpmyadmin with PHP 7.3. Thanks @coderama, I changed libraries/DisplayResults.class.php line 855 from
// Move to the next page or to the last one
$endpos = $_SESSION['tmpval']['pos']
+ $_SESSION['tmpval']['max_rows'];
into
// Move to the next page or to the last one
$endpos = (int)$_SESSION['tmpval']['pos']
+ (int)$_SESSION['tmpval']['max_rows'];
Fixed.
483
votes
Answer
Solution:
Try this.
$sub_total = 0;
and within your loop now you can use this
$sub_total += ($item['quantity'] * $product['price']);
It should solve your problem.
534
votes
Answer
Solution:
Check if you’re not incrementing with some variable that its value is an empty string like ».
Example:
$total = '';
$integers = range(1, 5);
foreach($integers as $integer) {
$total += $integer;
}
578
votes
Answer
Solution:
I just looked at this page as I had this issue. For me I had floating point numbers calculated from an array but even after designating the variables as floating points the error was still given, here’s the simple fix and example code underneath which was causing the issue.
Example PHP
<?php
$subtotal = 0; //Warning fixed
$shippingtotal = 0; //Warning fixed
$price = array($row3['price']);
$shipping = array($row3['shipping']);
$values1 = array_sum($price);
$values2 = array_sum($shipping);
(float)$subtotal += $values1; // float is irrelevant $subtotal creates warning
(float)$shippingtotal += $values2; // float is irrelevant $shippingtotal creates warning
?>
649
votes
Answer
Solution:
$sn = 0;//increment the serial number, then add the sn to job
for($x = 0; $x<20; $x++)
{
$sn++;
$added_date = "10/10/10";
$job_title = "new job";
$salary = $sn*1000;
$cd = "27/10/2017";//the closing date
$ins = "some institution";//the institution for the vacancy
$notes = "some notes here";//any notes about the jobs
$sn_div = "<div class='sn_div'>".$sn."</div>";
$ad_div = "<div class='ad_div'>".$added_date."</div>";
$job_div = "<div class='job_div'>".$job_title."</div>";
$salary_div = "<div class='salary_div'>".$salary."</div>";
$cd_div = "<div class='cd_div'>".$cd."</div>";//cd means closing date
$ins_div = "<div class='ins_div'>".$ins."</div>";//ins means institution
$notes_div = "<div class='notes_div'>".$notes."</div>";
/*erroneous line*/$job_no = "job"+$sn;//to create the job rows
$$job_no = "<div class='job_wrapper'>".$sn_div.$ad_div.$job_div.$salary_div.$cd_div.$ins_div.$notes_div."</div>";
echo $$job_no;//and then echo each job
}
that’s the code I had which looped and created new html div elements. The code worked fine and the elements were formed, but i got the same warning in the error_log.
After reading the useful other answers, I figured that I was summing up a string and a number in the erroneous line. So I changed the code at that line to
/*erroneous line*/$job_no = "job"&&$sn;//this is the new variable that will create the job rows
Now the code works as earlier but with no warnings this time. Hope this example would be useful to someone.
227
votes
Answer
Solution:
Solve this error on WordPress
Warning: A non-numeric value encountered in C:XAMPPhtdocsaad-2wp-includesSimplePieParseDate.php on line 694
Simple solution here!
- locate a file of
wp-includesSimplePieParseDate.php
- find a line no. 694
- you show the code
$second = round($match[6] + $match[7] / pow(10, strlen($match[7])));
- and change this 3.) to this line
$second = round((int)$match[6] + (int)$match[7] / pow(10, strlen($match[7])));
330
votes
Answer
Solution:
$sub_total_price = 0;
foreach($booking_list as $key=>$value) {
$sub_total_price += ($price * $quantity);
}
echo $sub_total_price;
it’s working 100%
593
votes
Answer
Solution:
That’s happen usually when you con-cat strings with + sign. In PHP you can make concatenation using dot sign (.) So sometimes I accidentally put + sign between two strings in PHP, and it show me this error, since you can use + sign in numbers only.
908
votes
Answer
Solution:
PHP 7.1-7.4
This warning happens when you have a non-numeric string in an expression (probably{-code-1}
,-
,*
, or/
) where PHP is expecting to see another scalar (int, float, or bool). There are two likely situations where this happens:
- You did not mean to use an operation that expects a scalar. For example,
{-code-1}
(addition) when you meant.
(concatenation). - You were expecting a number, but the value you used was not even close to a number. Figure out what your non-number is, and handle accordingly.
- For example, if you have
echo 3 {-code-1} $variable
and your$variable
is the string"n/a"
, then you might decide to instead echo «not applicable». Or maybe you decide that all non-numeric values should be treated as 0 and cast to the .
- For example, if you have
Fix these warnings! In PHP 8, this becomes a fatal error: «Uncaught TypeError: Unsupported operand types».
PHP 8
Code that used to produce the warning «A non well formed numeric value encountered» in PHP 7.1-7.4 now gives this warning instead. This happens when you have a «trailing string», which is a string that starts with a number, but is followed by something non-numeric. (It will still do the math but you should fix this! In the future it may be upgraded to an error.) For example:
echo 3 {-code-1} "30 meters";
Output:
Warning: A non-numeric value encountered in […][…] on line X
33
408
votes
Answer
Solution:
Make sure that your column structure is INT.
451
votes
Answer
Solution:
If non-numeric value encountered in your code try below one.
The below code is converted to float.
$PlannedAmount = ''; // empty string ''
if(!is_numeric($PlannedAmount)) {
$PlannedAmount = floatval($PlannedAmount);
}
echo $PlannedAmount; //output = 0
222
votes
Answer
Solution:
in PHP if you use + for concatenation you will end up with this error. In php + is a arithmetic operator.
https://www.php.net/manual/en/language.operators.arithmetic.php
wrong use of + operator:
"<label for='content'>Content:</label>"+
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>"+$initcontent+"</textarea>'"+
"</div>";
use . for concatenation
$output = "<div class='from-group'>".
"<label for='content'>Content:</label>".
"<textarea class='form-control col-xs-12' rows='7'cols='100' id='content' name='content'>".$initcontent."</textarea>'".
"</div>";
2
votes
Answer
Solution:
You need to verify that you are dealing with a number:
if (is_numeric($item['quantity'])) {
if (is_numeric($product['price'])) {
echo $item['quantity'] * $product['price'];
} else {
echo $item['quantity']. $product['price'];
}
} else {
echo $item['quantity']. $product['price'];
}
808
votes
Answer
Solution:
$sub_total += ($item['quantity'] * $product['price']);
replace by:
$sub_total += floatval($item['quantity']) * floatval($product['price']);
Share solution ↓
Additional Information:
Date the issue was resolved:
2021-12-22
Link To Source
Link To Answer
People are also looking for solutions of the problem: too few arguments to function laravel
Didn’t find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
The NumberFormatException
is an unchecked exception in Java that occurs when an attempt is made to convert a string with an incorrect format to a numeric value. Therefore, this exception is thrown when it is not possible to convert a string to a numeric type (e.g. int, float). For example, this exception occurs if a string is attempted to be parsed to an integer but the string contains a boolean value.
Since the NumberFormatException
is an unchecked exception, it does not need to be declared in the throws
clause of a method or constructor. It can be handled in code using a try-catch block.
What Causes NumberFormatException
There can be various cases related to improper string format for conversion to numeric values. Some of them are:
Null input string
Integer.parseInt(null);
Empty input string
Integer.parseInt("");
Input string with leading/trailing whitespaces
Integer myInt = new Integer(" 123 ");
Input string with inappropriate symbols
Float.parseFloat("1,234");
Input string with non-numeric data
Integer.parseInt("Twenty Two");
Alphanumeric input string
Integer.parseInt("Twenty 2");
Input string exceeding the range of the target data type
Integer.parseInt("12345678901");
Mismatch of data type between input string and the target data type
Integer.parseInt("12.34");
NumberFormatException Example
Here is an example of a NumberFormatException
thrown when attempting to convert an alphanumeric string to an integer:
public class NumberFormatExceptionExample {
public static void main(String args[]) {
int a = Integer.parseInt("1a");
System.out.println(a);
}
}
In this example, a string containing both numbers and characters is attempted to be parsed to an integer, leading to a NumberFormatException:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1a"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:3)
Such operations should be avoided where possible by paying attention to detail and making sure strings attempted to be parsed to numeric values are appropriate and legal.
How to Handle NumberFormatException
The NumberFormatException
is an exception in Java, and therefore can be handled using try-catch blocks using the following steps:
- Surround the statements that can throw an
NumberFormatException
in try-catch blocks - Catch the
NumberFormatException
- Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message.
The code in the earlier example can be updated with the above steps:
public class NumberFormatExceptionExample {
public static void main(String args[]) {
try {
int a = Integer.parseInt("1a");
System.out.println(a);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormat Exception: invalid input string");
}
System.out.println("Continuing execution...");
}
}
Surrounding the code in try-catch blocks like the above allows the program to continue execution after the exception is encountered:
NumberFormat Exception: invalid input string
Continuing execution...
Track, Analyze and Manage Errors with Rollbar
Finding exceptions in your Java code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring, tracking and triaging, making fixing Java errors and exceptions easier than ever. Sign Up Today!
Потихоньку перехожу с PHP 5.6 на PHP7 (а точнее, сразу на 7.1). Ответ на вопрос «Зачем?» выходит за рамки данной заметки, поэтому сразу к сути. Если вы тоже решили обновить версию ПХП, вы можете столкнуться с рядом неприятных ошибок, одна из которых возникает из-за ужесточения правил работы числовых операторов, начиная с версии 7.1.
Новые ошибки уровней E_WARNING и E_NOTICE были добавлены при использовании некорректных строк с операторами, ожидающими числа (+ — * / ** % << >> | & ^) и их эквивалентами с присваиванием. Ошибка уровня E_NOTICE выдается, когда строка начинается с цифр, но далее содержит не цифровые символы, и ошибка уровня E_WARNING выдается тогда, когда строка вообще не содержит цифр.
В ПХП версии 7.0 и ниже следующий код будет работать без ошибок:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$a = 1 + '1text';
echo $a; // 2
$b = 1 + 'text';
echo $b; // 1
$c = '';
$d = 1 + $c;
echo $d; // 1
В ПХП версии 7.1 и выше это код выдаст нотис в 5-ой строке, а также ворнинги в 8-ой и 12-ой:
Notice: A non well formed numeric value encountered in test.php on line 5
2
Warning: A non-numeric value encountered in test.php on line 8
1
Warning: A non-numeric value encountered in test.php on line 12
1
Первые два случая особых проблем не вызывают, потому что, если у вас в проекте встречается код, в котором математические операции выполняются над буквами, проблема явно не в ПХП.
А вот третий случай — числовые операции с пустой строкой — часто встречается в реальных проектах. Пустая строка в подобных случаях всегда считалась нулём. Так может быть, например, если вы берёте какое-то числовое значение из конфига, а оно не заполнено. Я заметил, что даже многие библиотеки подвержены данной проблеме.
Решение — одновременно простое и сложное. Нужно добавить явное приведение типа:
$c = '';
$d = 1 + (int)$c;
Проблема в том, что это приходится делать вручную, отследить все такие места автоматически, увы, не получится. И это ворнинг, а не нотис, поэтому отключение через error_reporting(E_ALL & ~E_NOTICE); не сработает. Или надо отключать все ворнинги, а это очень плохая идея.