简体   繁体   English

在 Oracle pro*c 中将双精度转换为字符串

[英]Converting double to string in Oracle pro*c

Is there any way to convert a double value to string without losing any digit in Oracle pro*c?有没有办法将双精度值转换为字符串而不会在 Oracle pro*c 中丢失任何数字? The precision varies as the column from which value is fetched is NUMBER(10,8)精度随着从中获取值的列是 NUMBER(10,8) 而变化

Like it was mentioned in comments you can use TO_CHAR to convert to a string.就像评论中提到的那样,您可以使用 TO_CHAR 转换为字符串。 In Pro*C it would look something like this:在 Pro*C 中,它看起来像这样:

EXEC SQL DECLARE num_test_cursor CURSOR FOR SELECT TO_CHAR(num) FROM numtest; 

Then you can fetch it into a variable:然后你可以把它提取到一个变量中:

EXEC SQL FETCH num_test_cursor INTO :number_string; 

Finally with最后与

number_string[strcspn(number_string, " ")] = '\0';

you can remove all padding space characters at the end.您可以删除末尾的所有填充空格字符。

Test测试

Create a table in an SQL client, eg SQLPlus, and fill it with some test entries:在 SQL 客户端(例如 SQLPlus)中创建一个表,并用一些测试条目填充它:

CREATE TABLE numtest ( num NUMBER(10,8));
INSERT INTO numtest VALUES (99.99999999);
INSERT INTO numtest VALUES (3.141592654);
INSERT INTO numtest VALUES (0.00000001);
INSERT INTO numtest VALUES (1.23);

Complete, Self-contained Pro*C Program完整、自包含的 Pro*C 程序

exec sql begin declare section;  
char *connectString = "scott/tiger@pdb";
int limit; 
char number_string[11 + 1]; //number(10,8) + NUL 
exec sql end declare section;  
exec sql include sqlca;  

#include<stdio.h>  
#include<conio.h>  
#include<stdlib.h>  

int main(void) {  
    exec sql connect :connectString;
    if(sqlca.sqlcode == 0) {  
        printf("connected to db\n");  
    } else {  
        fprintf(stderr, "failed:%s (error code=%d)\n", sqlca.sqlerrm.sqlerrmc, sqlca.sqlcode);  
        exit(1);
    }
    EXEC SQL SELECT COUNT(*) INTO :limit FROM numtest; 
    printf("row count: %d\n", limit);

    EXEC SQL DECLARE num_test_cursor CURSOR FOR SELECT TO_CHAR(num) FROM numtest; 
    EXEC SQL FOR :limit OPEN num_test_cursor; 

    int row;
    for(row = 0; row < limit; row++) {
        EXEC SQL FETCH num_test_cursor INTO :number_string; 
    
        number_string[strcspn(number_string, " ")] = '\0';
        printf("number as string: \"%s\"\n", number_string);
    }
    
    _getch();  

    return 0;
} 
    

The debug outputs of the program confirm the desired result:程序的调试输出确认了所需的结果:

connected to db
row count: 4
number as string: "99.99999999"
number as string: "3.14159265"
number as string: ".00000001"
number as string: "1.23"
 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM