Topic: invalid float if i use Str() (Read 2982 times)
I have found an interesting point if i convert with Str().
The following program demonstarte this. It conver a float(exact type double) to a string and the way back is not working, because it raises and EConvertError 0.0000000000000E+000 is an invalid float if you try to convert it back with StrToFloat().
Is this correct that str() produce a wrong string ?!
-
program Project1;
-
uses SysUtils;
-
var
-
String1: string;
-
Float1, Float2: Double;
-
begin
-
writeln(‘Start Testfloat’);
-
Float1 := 0.0;
-
Str(Float1,String1);
-
writeln(‘Float 1=<‘+String1+‘>’);
-
Float2:= StrToFloat(String1);
-
end.
BTW. I have found such a similar code in a fpc component This is the reason for my question.
Logged
regards
Andreas
StrToFloat uses the FormatSettings of your system. Many European countries use a comma for the DecimalSeparator — here 0.0000E+00 in fact is an invalid numeric string, it should be 0,0000E+00.
Since StrToFloat (as well as the opposite conversion FloatToStr) has many overloads you can use an adjusted copy of the FormatSettings as last parameter:
-
function PointStrToFloat(s: String): Double;
-
var
-
fs: TFormatSettings;
-
begin
-
fs := FormatSettings;
-
fs.DecimalSeparator := ‘.’;
-
Result := StrToFloat(s, fs);
-
end;
-
function PointFloatToStr(x: Double): String;
-
var
-
fs: TFormatSettings;
-
begin
-
fs := FormatSettings;
-
fs.DecimalSeparator := ‘.’;
-
Result := FloatToStr(x, fs);
-
end;
Str() is an old Pascal function which existed before anybody was thinking of FormatSettings — it always uses a point as decimal separator. Its partner is the «val()» procedure — using it above PointStrToFloat() could be rewritten as
-
function PointStrToFloat(s: String): Double;
-
var
-
res: Integer;
-
begin
-
val(s, Result, res);
-
if res <> 0 then
-
raise EConvertError.Create(‘no valid numeric string’);
-
end;
« Last Edit: January 06, 2020, 10:53:03 am by wp »
Logged
So it is correct, the test fail in fpreport. the problem is this code here
-
function TFPReportVariable.GetValue: String;
-
begin
-
Case DataType of
-
rtBoolean : Result:=BoolToStr(AsBoolean,True);
-
rtInteger : Result:=IntToStr(AsInteger);
-
rtFloat : Str(AsFloat,Result);
-
rtCurrency : Str(AsCurrency,Result);
-
rtDateTime : Result:=DateTimeToISO8601(AsDateTime);
-
rtString : Result:=AsString
-
else
-
Raise EConvertError.CreateFmt(SErrUnknownResultType,[GetEnumName(TypeInfo(TResultType),Ord(DataType))])
-
end;
-
end;
it convert float and currency without the actual formatsettings. In the test of the fpreport it is using with formatsetting.
-
procedure TTestVariable.TestFloat;
-
Var
-
R : TFPExpressionResult;
-
begin
-
Variable.DataType:=rtFloat;
-
AssertEquals(‘Float type remains’,rtFloat,Variable.DataType);
-
AssertEquals(‘Float default value’,0.0,Variable.AsFloat);
-
AssertEquals(‘Float as string’,0.0,StrToFloat(Variable.Value)); // <- EConvertException
-
Variable.DataType:=rtBoolean;
-
Variable.AsFloat:=1.23;
-
AssertEquals(‘Float type remains’,rtFloat,Variable.DataType);
-
AssertEquals(‘Float as string’,1.23,StrToFloat(Variable.Value));
-
AssertEquals(‘Float value’,1.23,Variable.AsFloat);
-
R:=Variable.AsExpressionResult;
-
AssertEquals(‘Correct result’,rtFloat,r.resulttype);
-
AssertEquals(‘Correct value’,1.23,r.resFloat);
-
ExpectException(‘Cannot fetch as other type’,EConvertError);
-
Variable.AsString;
-
end;
I see, converting a float to string and back is not an easy thing.
Logged
regards
Andreas
Since a report engine produces output for the application user, I think it should respect the FormatSettings on the user’s machine. Therefore, I consider usage of the Str() function in TFPReportVariable to be a bug (it should be FloatToStr()). Please report it to bugtracker.
There is another issue: I see in TestFloat that FPReport seems to call FPExpressionParser. This formula parser also requires a decimal point separator. I think FPExpressionParser should be generalized to accept any other decimal separator (and list separator etc.) — I did this for FPSpreadsheet, so, it is feasible.
« Last Edit: January 06, 2020, 11:20:33 am by wp »
Logged
It is one of the failed tests in Bugreport 0036519 Link: https://bugs.freepascal.org/view.php?id=36519
The dot/comma problem i have seen with a german csv file and the report too. But i want to have all testst running before i file more Bugs in fpreport. Michael have fixed some other issues in the last days (i discussed something on the mailinglist).
« Last Edit: January 06, 2020, 12:13:34 pm by af0815 »
Logged
regards
Andreas
Note that the original code provided indicates string as shortstring. That may be the cause.
-
{$mode delphi}{$H+}
-
program Project100;
-
uses SysUtils;
-
var
-
String1: string;
-
Float1, Float2: Double;
-
begin
-
writeln(‘Start Testfloat’);
-
Float1 := 0.0;
-
Str(Float1,String1);
-
writeln(‘Float 1=<‘+String1+‘>’);
-
Float2:= StrToFloat(String1);
-
end.
This works, because of {$H+}.
str() itself otherwise defaults to shortstring, but it does support AnsiString as well, provided you know what string type you are using : {$H+}
That bug report makes the same — wrong — assumption.
« Last Edit: January 06, 2020, 12:15:56 pm by Thaddy »
Logged
I actually get compliments for being rude… (well, Dutch, but that is the same)
I think you are on a english configured machine there it will be work. I have a german machine
and there it fails.
Logged
regards
Andreas
I think you are on a english configured machine
there it will be work. I have a german machine
and there it fails.
I also test on «German», since the Dutch language requires about the same . Plz follow my advice above: make sure your string type is correct and consistent.
« Last Edit: January 06, 2020, 12:20:49 pm by Thaddy »
Logged
I actually get compliments for being rude… (well, Dutch, but that is the same)
I don’t see what shortstring or ansistring have to do with the decimal separator. The test project running with a comma separator fails no matter whether the variable «string1» is an AnsiString or a ShortString:
-
program Project100;
-
uses
-
SysUtils;
-
var
-
String1: string[255];
-
// String1: string;
-
Float1, Float2: Double;
-
begin
-
FormatSettings.DecimalSeparator := ‘,’;
-
writeln(‘Start Testfloat’);
-
Float1 := 0.0;
-
Str(Float1,String1);
-
writeln(‘Float 1=<‘+String1+‘>’);
-
Float2:= StrToFloat(String1);
-
end.
Logged
Tested with the advice from Thaddy -> the same error.
You can test it in the full context, if you run the unittests (trunk) from fpc/packages/fcl-report/test/testfpreport.lpr or fpc/packages/fcl-report/test/guitestfpreport.lpr
The test TTestVariable.TestFloat is the correct one for this thread.
Logged
regards
Andreas
I don’t see what shortstring or ansistring have to do with the decimal separator. The test project running with a comma separator fails no matter whether the variable «string1» is an AnsiString or a ShortString:
And it does so also in Delphi (Dutch locale), as one would expect.
Bart
Logged
Logged
regards
Andreas
stkapler 0 / 0 / 0 Регистрация: 07.02.2018 Сообщений: 19 |
||||
1 |
||||
05.03.2018, 12:25. Показов 3650. Ответов 6 Метки lazarus, pascal (Все метки)
и сова мною любимый массив данных. есть массив, в который пользователь вводит числа из головы. нажимается кнопка — в другом массиве эти же числа преподносятся к степени. и вроде бы все хорошо, числа преподносятся. но иногда кое как и постоянно возникает ошибка: «проект project 1 вызвал класс исключения «econverterror» с сообщением: » » is an invalid float по адресу 1000507ba» код ниже:
0 |
dddoc 9 / 9 / 1 Регистрация: 25.06.2017 Сообщений: 51 |
||||||||
05.03.2018, 13:52 |
2 |
|||||||
У тебя, скорее всего, строка в Memo пустая попадается. Попробуй так
ps. Кстати, в Лазаре тип real — псевдоним типа Double, т.е. ты можешь писать так
0 |
0 / 0 / 0 Регистрация: 07.02.2018 Сообщений: 19 |
|
05.03.2018, 14:19 [ТС] |
3 |
тоже самое( Добавлено через 1 минуту 000000010005086A 48c744242000000000 movq $0x0,0x20(%rsp)
0 |
Модератор 8500 / 5659 / 2291 Регистрация: 21.01.2014 Сообщений: 24,267 Записей в блоге: 3 |
|
05.03.2018, 14:30 |
4 |
есть массив, в который пользователь вводит числа из головы А почему Вы тогда жестко ограничиваете пользователя, что он обязан ввести 10 чисел? А если он введет меньше — вы и получите свой вылет…
0 |
dddoc 9 / 9 / 1 Регистрация: 25.06.2017 Сообщений: 51 |
||||||
05.03.2018, 15:04 |
5 |
|||||
тоже самое(
зы. как и советовал D1973, сделай проверку в вводимом контроле на корректность данных перед обработкой (чтобы это было не пустое значение + это был вещественный тип) Миниатюры
Вложения
0 |
9 / 9 / 1 Регистрация: 25.06.2017 Сообщений: 51 |
|
05.03.2018, 15:08 |
6 |
Использовать динамический массив для примера вовсе не обязательно. А то он совсем утонет
0 |
D1973 |
05.03.2018, 15:09
|
Не по теме:
А то он совсем утонет
0 |
TDBEdit — » is an invalid float
Модератор: Модераторы
TDBEdit — » is an invalid float
Хочеться прояснить ситуацию с TDBEdit. TDBEdit связан с числовым полем. Если ввести в него число, затем очистить, то при выходе из этого элемента возникает исключение EConvertError: » is an invalid float. Приходится присваивать Null полю в обработчике OnEditingDone:
- Код: Выделить всё
if SQLQuery.State in [dsInsert, dsEdit] then
if DBEdit.Text = '' then
DBEdit.Field.Value := Null;
Похожая ситуация, если с DBEdit связано поле с типом Дата.
Компоненты используются стандартные.
Lazarus 0.9.30.2 + Firebird.
- 7bit
- новенький
- Сообщения: 22
- Зарегистрирован: 01.10.2011 12:35:52
Re: TDBEdit — » is an invalid float
Little_Roo » 25.12.2011 21:47:10
7bit писал(а):TDBEdit связан с числовым полем. Если ввести в него число, затем очистить, то при выходе из этого элемента возникает исключение
Не замечено ни разу
Использую порядка 300 tdbedit’ов — и в числовых значениях, и в строковых — полет нормальный….
Копайте код.
-
Little_Roo - энтузиаст
- Сообщения: 633
- Зарегистрирован: 27.02.2009 19:56:36
- Откуда: Санкт-Петербург
Вернуться в Lazarus
Кто сейчас на конференции
Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 12
Форум программистов Vingrad
Модераторы: Poseidon, Snowy, bems, MetalFan |
Поиск: |
|
Опции темы |
freenity |
|
||
Новичок Профиль Репутация: нет
|
в этой части происходит ошибка, когда нажимаю на кнопку, появляется мисаджБокс и говорит что эксэпшн. Что не так? Спасибо. |
||
|
|||
Matematik |
|
||
Эксперт Профиль Репутация: 17
|
Текст ошибки напиши |
||
|
|||
Alexeis |
|
||
Амеба Профиль
Репутация: 109
|
Разделитель целой и дробной части отличается от требуемого в strtofloat(); Добавлено @ 22:40 ——————— Vit вечная память. Обсуждение действий администрации форума производятся только в этом форуме гениальность идеи состоит в том, что ее невозможно придумать |
||
|
|||
freenity |
|
||
Новичок Профиль Репутация: нет
|
Вот текст ошибки:
Это сообщение отредактировал(а) freenity — 7.9.2006, 23:06 |
||
|
|||
Fedia |
|
||
Опытный Профиль
Репутация: 8
|
А ведь ты скорее всего совершенно прав. А я функцию strtofloat в примере не заменил ——————— Накануне решающей битвы |
||
|
|||
freenity |
|
||
Новичок Профиль Репутация: нет
|
Добавил, все равно та же ошибка |
||
|
|||
Fedia |
|
||
Опытный Профиль
Репутация: 8
|
Что содержит переменная numero перед строкой
? Посмотри в пошаговом режиме. ——————— Накануне решающей битвы |
||
|
|||
Alexeis |
|
||
Амеба Профиль
Репутация: 109
|
freenity, все намного проще
Просто функция GetWindowText(hwndEdit, pchar(numero), 255); — возвращает пустую строку ——————— Vit вечная память. Обсуждение действий администрации форума производятся только в этом форуме гениальность идеи состоит в том, что ее невозможно придумать |
||
|
|||
freenity |
|
||
Новичок Профиль Репутация: нет
|
Fedia, GetWindowText не возвращает пустую строку, попробывал мисаджем сразау после getwindowtext ошибка точно здесь: |
||
|
|||
volvo877 |
|
||
Эксперт Профиль Репутация: 14
|
freenity, тебя просили сказать,
, в смысле, какое значение… Откуда оно берется — это твои проблемы, и в данном случае — неважно… или тебе уже не нужна помощь? Телепаты, извини, в отпуске… Это сообщение отредактировал(а) volvo877 — 8.9.2006, 01:15 |
||
|
|||
Fedia |
|
||||
Опытный Профиль
Репутация: 8
|
Должен быть — это не ответ на мой вопрос. Посмотри точно, какое значение содержит переменная numero перед выполнением:
——————— Накануне решающей битвы |
||||
|
|||||
Alexeis |
|
||||
Амеба Профиль
Репутация: 109
|
показывает что строка пустая, а потому не может быть представлена вещественым числом. возможно нельзя передавать возвращаемый параметр ввиде pchar(numero) Добавлено @ 01:20 Добавлено @ 01:24
нужен указатель на выделеный буфер, а не пустой указатель, вот ничего и не копируется. ——————— Vit вечная память. Обсуждение действий администрации форума производятся только в этом форуме гениальность идеи состоит в том, что ее невозможно придумать |
||||
|
|||||
Fedia |
|
||||
Опытный Профиль
Репутация: 8
|
Блин, я и не заметил, что он отредактировал этот постинг
Если человек не может сказать, какое значение содержится в переменной, то маловероятно, что это ему поможет. alexeis1, молодец ——————— Накануне решающей битвы |
||||
|
|||||
freenity |
|
||
Новичок Профиль Репутация: нет
|
Спасибо заработало Это сообщение отредактировал(а) freenity — 8.9.2006, 02:06 |
||
|
|||
|
Правила форума «Delphi: Общие вопросы» | |
|
Запрещается! 1. Публиковать ссылки на вскрытые компоненты 2. Обсуждать взлом компонентов и делиться вскрытыми компонентами
Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Snowy, MetalFan, bems, Poseidon, Rrader. |
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) |
0 Пользователей: |
« Предыдущая тема | Delphi: Общие вопросы | Следующая тема » |
I’ve been following a lesson on how to constrain images within an activity window and, when I try to apply an aspect ratio of 1:1, the image moves away from it’s original intended location on the activity and up into the left hand corner of the activity as a 0dp x 0dp ImageView.
My code is saying this is an error of "Invalid Float"
:
app:layout_constraintDimensionRatio="1:1"
This is mysterious to me because the system ALSO tells me that the ratio can be listed as either a FLOAT or a RATIO. Someone tell me I’m not crazy and when I learned ratios as a kid they were separated by a colon.
I’ve removed the ImageViews multiple times and re-added constraints an equal RATIO amount of times. Still, Android Studio doesn’t know what a 1:1 ratio is. The constraint goes as follows:
Top Constraint
+ ImageView1
+ ImageView2
Bottom constraint
app:layout_constraintDimensionRatio="1:1"
Invalid Float
The ImageView is at the top of my activity window as a 0dp x 0dp image.
asked Jul 25, 2019 at 18:48
1
It seems that there was a change in the constraint layout implementation.
app:layout_constraintDimensionRatio=»W,661:165″
This does not work any longer. I get the message «Invalid float»
The solution is simple. This parameter now requires a float value. In the above example, all we have to do is to divide 665/165 = 4.006 (We can round the value to 4)
So this line now works as expected:
app:layout_constraintDimensionRatio=»4″
Hope this answer helps.
answered Jun 24, 2020 at 4:26
NickNick
1,3931 gold badge14 silver badges22 bronze badges
This question is totally valid and I couldn’t find an answer for that anywhere else.
The thing is, if you know what is a ratio and read the error carefully you notice that, for some reason, the layout wants you to use a float notation for it.
For example, if you want a ratio of 2:1 you want the width to be two times the height. Therefore you provide the ration like this width/height
, since you want it 1 by 1 just put app:layout_constraintDimensionRatio="1"
and be happy.
tl;dr: ratio 1:1 = 1/1 = 1 -> app:layout_constraintDimensionRatio="1"
answered Aug 15, 2019 at 19:54
I am not sure if this is exactly what you are looking for or if helps at all, but here is how I successfully was able to use it for my application. I believe the problem you are having might be the lack of constraints you have on the ImageView you are working with (which is why it might be going towards the top left of the screen). However, I cannot say this with confidence since I cannot see your code. I may be wrong since I am not a professional, but that is my best guess for now.
<ImageView
android:id="@+id/userPicture"
android:src="@drawable/user_picture"
android:contentDescription="Update later"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:layout_marginTop="40dp"
android:layout_marginBottom="15dp"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/currentTrackPlayingText"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintDimensionRatio="1:1" />
This produces the following that is constrained to other aspects of on the screen (Apologies, I do not have enough rep to show the image here).
link to example produced by above
answered Jul 25, 2019 at 19:29