부동 소수점 구성 요소가 .00 Sprintf/Printf 인 경우 소수점 만 표시

StackOverflow https://stackoverflow.com/questions/838064

  •  10-07-2019
  •  | 
  •  

문제

플로팅 포인트 번호를 포맷하고 있지만 관련 부동 소수점 번호가 없으면 정수로 나타나기를 원합니다.

  • 1.20-> 1.2x
  • 1.78-> 1.78x
  • 0.80-> 0.8x
  • 2.00-> 2x

나는 약간의 동선으로 이것을 달성 할 수 있지만 sprintf-이 작업을 수행하는 방법?

나는 루비처럼 오히려 게으르게하고 있습니다.

("%0.2fx" % (factor / 100.0)).gsub(/\.?0+x$/,'x')
도움이 되었습니까?

해결책

당신은 사용하고 싶습니다 %g 대신에 %f:

"%gx" % (factor / 100.00)

다른 팁

%g 및 %f를 혼합하고 일치시킬 수 있습니다.

"%g" % ("%.2f" % number)

레일을 사용하는 경우 Rails의 NumberHelper 방법을 사용할 수 있습니다.http://api.rubyonrails.org/classes/actionview/helpers/numberhelper.html

number_with_precision(13.001, precision: 2, strip_insignificant_zeros: true)
# => 13
number_with_precision(13.005, precision: 2, strip_insignificant_zeros: true)
# => 13.01

정밀도는이 경우 소수점 이후의 모든 숫자를 의미하기 때문에주의하십시오.

나는 끝났다

price = price.round(precision)
price = price % 1 == 0 ? price.to_i : price.to_f

이렇게하면 문자열 대신 숫자를 얻습니다

방금 이것을 발견했는데 위의 수정 사항은 작동하지 않았지만 이것을 생각해 냈습니다.

def format_data(data_element)
    # if the number is an in, dont show trailing zeros
    if data_element.to_i == data_element
         return "%i" % data_element
    else
    # otherwise show 2 decimals
        return "%.2f" % data_element
    end
end

다른 방법은 다음과 같습니다.

decimal_precision = 2
"%.#{x.truncate.to_s.size + decimal_precision}g" % x

또는 멋진 원 라이너로서 :

"%.#{x.truncate.to_s.size + 2}g" % x

레일로 쉽게 : http://api.rubyonrails.org/classes/actionview/helpers/numberhelper.html#method-i-number_with_precision

number_with_precision(value, precision: 2, significant: false, strip_insignificant_zeros: true)

나는 Ruby on Rails에서 플로트 또는 소수점 숫자를 자르고 (근사치가 아닌) 기능을 찾고 있었고 다음을 수행 할 수있는 솔루션을 찾았습니다.

여러분은 콘솔에서 시험해 볼 수 있습니다.

>> a=8.88
>> (Integer(a*10))*0.10
>> 8.8

나는 그것이 누군가를 돕기를 바랍니다. :-)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top