Home > Software design >  how to convert float to close it number in (int)
how to convert float to close it number in (int)

Time:10-13

float index = 0.0588 * L - 0.296 * S - 15.8;
int i = index;
printf("%i",i);
  1. //index equal 11.706415

  2. //when I convert the index to int the int will equal 11 "I want it to be 12"

CodePudding user response:

When you cast a float to an int it will be truncated. You can use roundf() then cast the return value to an int:

#include <math.h>
#include <stdio.h>

int main(void) {
    float index = 11.706415;
    printf("truncated: %d\n"
           "rounded:   %d\n",
           (int) index,
           (int) roundf(index));
}

CodePudding user response:

Your existing code rounds toward zero, also known as integer truncation. You appear to what some form of round to nearest, but you didn't specify which.


In this particular case, you can use

printf( "%.0f", index );

By default, this rounds to nearest, half to even.


This rounds to nearest, half away from zero.

#include <math.h>   // Also need to link math lib (e.g. using -lm)

int i = lroundf( index );

This rounds to nearest, half up.

int i = index   0.5;

input round
to nearest
half to even
round
to nearest
half away from zero
round
to nearest
half up
-7.5 -8 -8 -7
-6.5 -6 -7 -6
6.5 6 7 7
7.5 8 8 8
  •  Tags:  
  • c
  • Related