Вопрос

I am using FMDatabase in my application and I have a small error when I try to insert these values -0.02, -0.01, -0.03.

I've tried to insert a simple plain query with exact values which is working, but when I had tried to insert values above with FMDatabase I got -0.019999999, 0.009999999. Can anyone suggest me how to fix this issue?

In the code below I got -0.02, so I don't know where is the problem:

if (strcmp([obj objCType], @encode(BOOL)) == 0) {
    sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0));
}
else if (strcmp([obj objCType], @encode(int)) == 0) {
    sqlite3_bind_int64(pStmt, idx, [obj longValue]);
}
else if (strcmp([obj objCType], @encode(long)) == 0) {
    sqlite3_bind_int64(pStmt, idx, [obj longValue]);
}
else if (strcmp([obj objCType], @encode(long long)) == 0) {
    sqlite3_bind_int64(pStmt, idx, [obj longLongValue]);
}
else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) {
    sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]);
}
else if (strcmp([obj objCType], @encode(float)) == 0) {
    float fl = [obj floatValue]; // the values is -0.02
    sqlite3_bind_double(pStmt, idx, [obj floatValue]);
}
else if (strcmp([obj objCType], @encode(double)) == 0) {
    sqlite3_bind_double(pStmt, idx, [obj doubleValue]);
}

My plain example query which is working:

INSERT INTO Transactions VALUES('aaaaaa','aaaaaa',0,-0.02,1,1,'0','0',1,'0','0','aa');

Prepared statement:

INSERT INTO UTransaction (id, note, data, price, repeat, forecast, cat_id, info_id, mutable, rem_id, original_id, is_id) VALUES (:id, :note, :data, :price, :repeat, :forecast, :cat_id, :info_id, :mutable, :rem_id, :original_id, :is_id)

Это было полезно?

Решение

You can not store float accurately into database. Float values always create problem of rounding. You should use decimal or numeric type for it.

While assigning the value do it by following way:

else if (strcmp([obj objCType], @encode(float)) == 0) {
    float fl = floorf(([obj floatValue]*100)/100); // the values is -0.02
    sqlite3_bind_double(pStmt, idx, [obj floatValue]);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top