Problem with sprintf when convert float to a string

General discussion on mikroC PRO for dsPIC30/33 and PIC24.
Post Reply
Author
Message
ngodinhnhan
Posts: 4
Joined: 23 Feb 2023 07:12

Problem with sprintf when convert float to a string

#1 Post by ngodinhnhan » 23 Feb 2023 07:24

Hi all,
I am currently using MikroC PRO for dsPIC v.7.1.0 for dsPIC30F4013 chip.
I want to convert a float number into a string, then display on a LCD. Here is my code:
[double result;
result = 35154239.81;
sprintf(txt3,"%.2Lf",result);
Lcd_Out(2,1,txt3);][/code]

A problem is that my LCD always display as 35154240.00 instead of 35154239.81;

I think there might some settings in MikroC software that effect on the function sprintf.

Any one please help me to fix this error ?

Many thanks in advanced.

Here are my full code:

[// Lcd module connections
sbit LCD_RS at LATD0_bit;
sbit LCD_EN at LATD1_bit;
sbit LCD_D4 at LATB0_bit;
sbit LCD_D5 at LATB1_bit;
sbit LCD_D6 at LATB2_bit;
sbit LCD_D7 at LATB3_bit;

sbit LCD_RS_Direction at TRISD0_bit;
sbit LCD_EN_Direction at TRISD1_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;
// End Lcd module connections

#define INT2_pin LATD9_bit

double result;
char txt3[20]="";

void INT2_Init()
{
INT2_dir = 1; // INT2 direction
INT2_pin = 0; // INT2 direction
IPC5 = 0x1000; // Interrupt is priority 1
INT2EP_bit = 1; // 1 = Interrupt on negative edge; 0 = Interrupt on positive edge
INT2IE_bit = 1;
}
void main() {

ADPCFG = 0xFFFF; // Configure AN pins as digital I/O

INT2_Init();

Delay_ms(1000);
Lcd_Cmd(_LCD_CLEAR);
Lcd_Out(1,1,"2023/02/23");
Delay_ms(1000);
while(1)
{}
}
// Interrupt routine
void External_Interrupt_2() iv IVT_ADDR_INT2INTERRUPT ics ICS_AUTO
{
result = 35154239.81;
sprintf(txt3,"%Lf",result);
Lcd_Cmd(_LCD_CLEAR);
Lcd_Out(2,1,txt3);

INT2IF_bit = 0;
}][/code]

steve42lawson
Posts: 183
Joined: 06 Mar 2008 17:35
Location: St. George, UT
Contact:

Re: Problem with sprintf when convert float to a string

#2 Post by steve42lawson » 26 Feb 2023 06:50

Try removing the 'L' from the format specification:

Code: Select all

sprintf(txt3,"%.2f",result);
The 'L' is only specified for integer types:
The optional characters l or L may immediately precede conversion_type to respectively specify long versions of the integer types d, i, u, o, x, and X.
Humility is the lack of the desire to impress, not the lack of being impressive.

ngodinhnhan
Posts: 4
Joined: 23 Feb 2023 07:12

Re: Problem with sprintf when convert float to a string

#3 Post by ngodinhnhan » 26 Feb 2023 07:36

Hi
I was trying to remove "L" character but unfortunately, i still got same error.

Post Reply

Return to “mikroC PRO for dsPIC30/33 and PIC24 General”